Revamp package testing.
[scons.git] / SConstruct
1 #
2 # SConstruct file to build scons packages during development.
3 #
4
5 #
6 # Copyright (c) 2001, 2002 Steven Knight
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining
9 # a copy of this software and associated documentation files (the
10 # "Software"), to deal in the Software without restriction, including
11 # without limitation the rights to use, copy, modify, merge, publish,
12 # distribute, sublicense, and/or sell copies of the Software, and to
13 # permit persons to whom the Software is furnished to do so, subject to
14 # the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included
17 # in all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
20 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
21 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 #
27
28 import distutils.util
29 import os
30 import os.path
31 import stat
32 import string
33 import sys
34 import time
35
36 project = 'scons'
37 default_version = '0.05'
38
39 Default('.')
40
41 #
42 # An internal "whereis" routine to figure out if we have a
43 # given program available.  Put it in the "cons::" package
44 # so subsidiary Conscript files can get at it easily, too.
45 #
46
47 def whereis(file):
48     for dir in string.split(os.environ['PATH'], os.pathsep):
49         f = os.path.join(dir, file)
50         if os.path.isfile(f):
51             try:
52                 st = os.stat(f)
53             except:
54                 continue
55             if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
56                 return f
57     return None
58
59 #
60 # We let the presence or absence of various utilities determine
61 # whether or not we bother to build certain pieces of things.
62 # This will allow people to still do SCons work even if they
63 # don't have Aegis or RPM installed, for example.
64 #
65 aegis = whereis('aegis')
66 aesub = whereis('aesub')
67 rpm = whereis('rpm')
68 dh_builddeb = whereis('dh_builddeb')
69 fakeroot = whereis('fakeroot')
70
71 # My installation on Red Hat doesn't like any debhelper version
72 # beyond 2, so let's use 2 as the default on any non-Debian build.
73 if os.path.isfile('/etc/debian_version'):
74     dh_compat = 3
75 else:
76     dh_compat = 2
77
78 #
79 # Now grab the information that we "build" into the files (using sed).
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 try:
96     revision = ARGUMENTS['version']
97 except:
98     if aesub:
99         revision = os.popen(aesub + " \\$version", "r").read()[:-1]
100     else:
101         revision = default_version
102
103 a = string.split(revision, '.')
104 arr = [a[0]]
105 for s in a[1:]:
106     if len(s) == 1:
107         s = '0' + s
108     arr.append(s)
109 revision = string.join(arr, '.')
110
111 # Here's how we'd turn the calculated $revision into our package $version.
112 # This makes it difficult to coordinate with other files (debian/changelog
113 # and rpm/scons.spec) that hard-code the version number, so just go with
114 # the flow for now and hard code it here, too.
115 #if len(arr) >= 2:
116 #    arr = arr[:-1]
117 #def xxx(str):
118 #    if str[0] == 'C' or str[0] == 'D':
119 #        str = str[1:]
120 #    while len(str) > 2 and str[0] == '0':
121 #        str = str[1:]
122 #    return str
123 #arr = map(lambda x, xxx=xxx: xxx(x), arr)
124 #version = string.join(arr, '.')
125 version = default_version
126
127 try:
128     change = ARGUMENTS['change']
129 except:
130     if aesub:
131         change = os.popen(aesub + " \\$change", "r").read()[:-1]
132     else:
133         change = default_version
134
135 python_ver = sys.version[0:3]
136
137 platform = distutils.util.get_platform()
138
139 if platform == "win32":
140     archsuffix = "zip"
141 else:
142     archsuffix = "tar.gz"
143
144 ENV = { 'PATH' : os.environ['PATH'] }
145 if os.environ.has_key('AEGIS_PROJECT'):
146     ENV['AEGIS_PROJECT'] = os.environ['AEGIS_PROJECT']
147
148 lib_project = os.path.join("lib", project)
149
150 unpack_dir = os.path.join(os.getcwd(), "build", "unpack")
151
152 test_arch_dir = os.path.join(os.getcwd(),
153                              "build",
154                              "test-%s" % string.replace(archsuffix, '.', '-'))
155
156 test_src_arch_dir = os.path.join(os.getcwd(),
157                                  "build",
158                                  "test-src-%s" % string.replace(archsuffix,
159                                                                 '.',
160                                                                 '-'))
161
162 test_rpm_dir = os.path.join(os.getcwd(), "build", "test-rpm")
163
164 test_deb_dir = os.path.join(os.getcwd(), "build", "test-deb")
165
166 def SCons_revision(target, source, env):
167     """Interpolate specific values from the environment into a file.
168     
169     This is used to copy files into a tree that gets packaged up
170     into the source file package.
171     """
172     print "SCons_revision() < %s > %s" % (source[0], target)
173     inf = open(source[0], 'rb')
174     outf = open(target, 'wb')
175     for line in inf.readlines():
176         # Note:  We construct the __*__ substitution strings here
177         # so that they don't get replaced when this file gets
178         # copied into the tree for packaging.
179         line = string.replace(line, '_' + '_DATE__', env['DATE'])
180         line = string.replace(line, '_' + '_DEVELOPER__', env['DEVELOPER'])
181         line = string.replace(line, '_' + '_FILE__', source[0])
182         line = string.replace(line, '_' + '_REVISION__', env['REVISION'])
183         line = string.replace(line, '_' + '_VERSION__', env['VERSION'])
184         outf.write(line)
185     inf.close()
186     outf.close()
187     os.chmod(target, os.stat(source[0])[0])
188
189 revbuilder = Builder(name = 'SCons_revision', action = SCons_revision)
190
191 env = Environment(
192                    ENV           = ENV,
193  
194                    DATE          = date,
195                    DEVELOPER     = developer,
196                    REVISION      = revision,
197                    VERSION       = version,
198                    DH_COMPAT     = dh_compat,
199
200                    BUILDERS      = [ revbuilder ],
201                  )
202
203 #
204 # Define SCons packages.
205 #
206 # In the original, more complicated packaging scheme, we were going
207 # to have separate packages for:
208 #
209 #       python-scons    only the build engine
210 #       scons-script    only the script
211 #       scons           the script plus the build engine
212 #
213 # We're now only delivering a single "scons" package, but this is still
214 # "built" as two sub-packages (the build engine and the script), so
215 # the definitions remain here, even though we're not using them for
216 # separate packages.
217 #
218
219 python_scons = {
220         'pkg'           : 'python-' + project,
221         'src_subdir'    : 'engine',
222         'inst_subdir'   : os.path.join('lib', 'python1.5', 'site-packages'),
223
224         'debian_deps'   : [
225                             'debian/rules',
226                             'debian/control',
227                             'debian/changelog',
228                             'debian/copyright',
229                             'debian/python-scons.postinst',
230                             'debian/python-scons.prerm',
231                           ],
232
233         'files'         : [ 'LICENSE.txt',
234                             'README.txt',
235                             'setup.cfg',
236                             'setup.py',
237                           ],
238
239         'filemap'       : {
240                             'LICENSE.txt' : '../LICENSE.txt'
241                           },
242 }
243
244 #
245 # The original packaging scheme would have have required us to push
246 # the Python version number into the package name (python1.5-scons,
247 # python2.0-scons, etc.), which would have required a definition
248 # like the following.  Leave this here in case we ever decide to do
249 # this in the future, but note that this would require some modification
250 # to src/engine/setup.py before it would really work.
251 #
252 #python2_scons = {
253 #        'pkg'          : 'python2-' + project,
254 #        'src_subdir'   : 'engine',
255 #        'inst_subdir'  : os.path.join('lib', 'python2.1', 'site-packages'),
256 #
257 #        'debian_deps'  : [
258 #                           'debian/rules',
259 #                           'debian/control',
260 #                           'debian/changelog',
261 #                           'debian/copyright',
262 #                           'debian/python2-scons.postinst',
263 #                           'debian/python2-scons.prerm',
264 #                          ],
265 #
266 #        'files'        : [
267 #                            'LICENSE.txt',
268 #                            'README.txt',
269 #                            'setup.cfg',
270 #                            'setup.py',
271 #                          ],
272 #        'filemap'      : {
273 #                            'LICENSE.txt' : '../LICENSE.txt',
274 #                          },
275 #}
276 #
277
278 scons_script = {
279         'pkg'           : project + '-script',
280         'src_subdir'    : 'script',
281         'inst_subdir'   : 'bin',
282
283         'debian_deps'   : [
284                             'debian/rules',
285                             'debian/control',
286                             'debian/changelog',
287                             'debian/copyright',
288                             'debian/python-scons.postinst',
289                             'debian/python-scons.prerm',
290                           ],
291
292         'files'         : [
293                             'LICENSE.txt',
294                             'README.txt',
295                             'setup.cfg',
296                             'setup.py',
297                           ],
298
299         'filemap'       : {
300                             'LICENSE.txt' : '../LICENSE.txt',
301                             'scons'       : 'scons.py',
302                            }
303 }
304
305 scons = {
306         'pkg'           : project,
307
308         'debian_deps'   : [ 
309                             'debian/rules',
310                             'debian/control',
311                             'debian/changelog',
312                             'debian/copyright',
313                             'debian/scons.postinst',
314                             'debian/scons.prerm',
315                           ],
316
317         'files'         : [ 
318                             'CHANGES.txt',
319                             'LICENSE.txt',
320                             'README.txt',
321                             'RELEASE.txt',
322                             'os_spawnv_fix.diff',
323                             'scons.1',
324                             'script/scons.bat',
325                             'setup.cfg',
326                             'setup.py',
327                           ],
328
329         'filemap'       : {
330                             'scons.1' : '../doc/man/scons.1',
331                           },
332
333         'subpkgs'       : [ python_scons, scons_script ],
334
335         'subinst_dirs'  : {
336                              'python-' + project : lib_project,
337                              project + '-script' : 'bin',
338                            },
339 }
340
341 src_deps = []
342 src_files = []
343
344 for p in [ scons ]:
345     #
346     # Initialize variables with the right directories for this package.
347     #
348     pkg = p['pkg']
349     pkg_version = "%s-%s" % (pkg, version)
350
351     src = 'src'
352     if p.has_key('src_subdir'):
353         src = os.path.join(src, p['src_subdir'])
354
355     build = os.path.join('build', pkg)
356
357     #
358     # Read up the list of source files from our MANIFEST.in.
359     # This list should *not* include LICENSE.txt, MANIFEST,
360     # README.txt, or setup.py.  Make a copy of the list for the
361     # destination files.
362     #
363     src_files = map(lambda x: x[:-1],
364                     open(os.path.join(src, 'MANIFEST.in')).readlines())
365     dst_files = src_files[:]
366
367     if p.has_key('subpkgs'):
368         #
369         # This package includes some sub-packages.  Read up their
370         # MANIFEST.in files, and add them to our source and destination
371         # file lists, modifying them as appropriate to add the
372         # specified subdirs.
373         #
374         for sp in p['subpkgs']:
375             ssubdir = sp['src_subdir']
376             isubdir = p['subinst_dirs'][sp['pkg']]
377             f = map(lambda x: x[:-1],
378                     open(os.path.join(src, ssubdir, 'MANIFEST.in')).readlines())
379             src_files.extend(map(lambda x, s=ssubdir: os.path.join(s, x), f))
380             dst_files.extend(map(lambda x, i=isubdir: os.path.join(i, x), f))
381             for k in sp['filemap'].keys():
382                 f = sp['filemap'][k]
383                 if f:
384                     k = os.path.join(sp['src_subdir'], k)
385                     p['filemap'][k] = os.path.join(sp['src_subdir'], f)
386
387     #
388     # Now that we have the "normal" source files, add those files
389     # that are standard for each distribution.  Note that we don't
390     # add these to dst_files, because they don't get installed.
391     # And we still have the MANIFEST to add.
392     #
393     src_files.extend(p['files'])
394
395     #
396     # Now run everything in src_file through the sed command we
397     # concocted to expand __FILE__, __VERSION__, etc.
398     #
399     for b in src_files:
400         s = p['filemap'].get(b, b)
401         env.SCons_revision(os.path.join(build, b), os.path.join(src, s))
402
403     #
404     # NOW, finally, we can create the MANIFEST, which we do
405     # by having Python spit out the contents of the src_files
406     # array we've carefully created.  After we've added
407     # MANIFEST itself to the array, of course.
408     #
409     src_files.append("MANIFEST")
410     def copy(target, source, **kw):
411         global src_files
412         src_files.sort()
413         f = open(target, 'wb')
414         for file in src_files:
415             f.write(file + "\n")
416         f.close()
417         return 0
418     env.Command(os.path.join(build, 'MANIFEST'),
419                 os.path.join(src, 'MANIFEST.in'),
420                 copy)
421
422     #
423     # Use the Python distutils to generate the packages.
424     #
425     archive = os.path.join(build, 'dist', "%s.%s" % (pkg_version, archsuffix))
426     platform_archive = os.path.join(build,
427                                     'dist',
428                                     "%s.%s.%s" % (pkg_version,
429                                                   platform,
430                                                   archsuffix))
431     win32_exe = os.path.join(build, 'dist', "%s.win32.exe" % pkg_version)
432
433     src_deps.append(archive)
434
435     build_targets = [ platform_archive, archive, win32_exe ]
436     install_targets = build_targets[:]
437
438     # We can get away with calling setup.py using a directory path
439     # like this because we put a preamble in it that will chdir()
440     # to the directory in which setup.py exists.
441     bdist_dirs = [
442         os.path.join(build, 'build', 'lib'),
443         os.path.join(build, 'build', 'scripts'),
444     ]
445     setup_py = os.path.join(build, 'setup.py')
446     commands = [
447         "rm -rf %s && python %s bdist" %
448             (string.join(map(lambda x: str(x), bdist_dirs)), setup_py),
449         "python %s sdist" % setup_py,
450         "python %s bdist_wininst" % setup_py,
451     ]
452
453     if rpm:
454         topdir = os.path.join(os.getcwd(), build, 'build',
455                               'bdist.' + platform, 'rpm')
456
457         BUILDdir = os.path.join(topdir, 'BUILD', pkg + '-' + version)
458         RPMSdir = os.path.join(topdir, 'RPMS', 'noarch')
459         SOURCESdir = os.path.join(topdir, 'SOURCES')
460         SPECSdir = os.path.join(topdir, 'SPECS')
461         SRPMSdir = os.path.join(topdir, 'SRPMS')
462
463         specfile = os.path.join(SPECSdir, "%s-1.spec" % pkg_version)
464         sourcefile = os.path.join(SOURCESdir,
465                                   "%s.%s" % (pkg_version, archsuffix));
466         rpm = os.path.join(RPMSdir, "%s-1.noarch.rpm" % pkg_version)
467         src_rpm = os.path.join(SRPMSdir, "%s-1.src.rpm" % pkg_version)
468
469         env.InstallAs(specfile, os.path.join('rpm', "%s.spec" % pkg))
470         env.InstallAs(sourcefile, archive)
471
472         targets = [ rpm, src_rpm ]
473         cmd = "rpm --define '_topdir $(%s$)' -ba $SOURCES" % topdir
474         if not os.path.isdir(BUILDdir):
475             cmd = ("$( mkdir -p %s; $)" % BUILDdir) + cmd
476         env.Command(targets, specfile, cmd)
477         env.Depends(targets, sourcefile)
478
479         install_targets.extend(targets)
480
481         dfiles = map(lambda x, d=test_rpm_dir: os.path.join(d, 'usr', x),
482                      dst_files)
483         env.Command(dfiles,
484                     rpm,
485                     "rpm2cpio $SOURCES | (cd %s && cpio -id)" % test_rpm_dir)
486
487     build_src_files = map(lambda x, b=build: os.path.join(b, x), src_files)
488
489     if dh_builddeb and fakeroot:
490         # Debian builds directly into build/dist, so we don't
491         # need to add the .debs to the install_targets.
492         deb = os.path.join('build', 'dist', "%s_%s-1_all.deb" % (pkg, version))
493         env.Command(deb, build_src_files, [
494             "fakeroot make -f debian/rules VERSION=$VERSION DH_COMPAT=$DH_COMPAT ENVOKED_BY_CONSTRUCT=1 binary-%s" % pkg,
495             "env DH_COMPAT=$DH_COMPAT dh_clean"
496                     ])
497         env.Depends(deb, p['debian_deps'])
498
499         dfiles = map(lambda x, d=test_deb_dir: os.path.join(d, 'usr', x),
500                      dst_files)
501         env.Command(dfiles,
502                     deb,
503                     "dpkg --fsys-tarfile $SOURCES | (cd %s && tar -xf -)" % test_deb_dir)
504
505     #
506     # Now set up creation and installation of the packages.
507     #
508     env.Command(build_targets, build_src_files, commands)
509     env.Install(os.path.join('build', 'dist'), install_targets)
510
511     #
512     # Unpack the archive created by the distutils into
513     # build/unpack/scons-{version}.
514     #
515     unpack_files = map(lambda x, u=unpack_dir, pv=pkg_version:
516                               os.path.join(u, pv, x),
517                        src_files)
518
519     #
520     # We'd like to replace the last three lines with the following:
521     #
522     #   tar zxf %< -C $unpack_dir
523     #
524     # but that gives heartburn to Cygwin's tar, so work around it
525     # with separate zcat-tar-rm commands.
526     env.Command(unpack_files, archive, [
527         "rm -rf %s" % os.path.join(unpack_dir, pkg_version),
528         "zcat $SOURCES > .temp",
529         "tar xf .temp -C %s" % unpack_dir,
530         "rm -f .temp",
531     ])
532
533     #
534     # Run setup.py in the unpacked subdirectory to "install" everything
535     # into our build/test subdirectory.  The runtest.py script will set
536     # PYTHONPATH so that the tests only look under build/test-{package},
537     # and under etc (for the testing modules TestCmd.py, TestSCons.py,
538     # and unittest.py).  This makes sure that our tests pass with what
539     # we really packaged, not because of something hanging around in
540     # the development directory.
541     #
542     # We can get away with calling setup.py using a directory path
543     # like this because we put a preamble in it that will chdir()
544     # to the directory in which setup.py exists.
545     dfiles = map(lambda x, d=test_arch_dir: os.path.join(d, x), dst_files)
546     env.Command(dfiles, unpack_files, [
547         "rm -rf %s" % os.path.join(unpack_dir, pkg_version, 'build'),
548         "rm -rf %s" % test_arch_dir,
549         "python %s install --prefix=%s" % (os.path.join(unpack_dir,
550                                                         pkg_version,
551                                                         'setup.py'),
552                                            test_arch_dir
553                                           ),
554     ])
555
556 #
557 # Documentation.
558 #
559 BuildDir('build/doc', 'doc')
560
561 Export('env', 'whereis')
562
563 SConscript('build/doc/SConscript');
564
565 #
566 # If we're running in the actual Aegis project, pack up a complete
567 # source archive from the project files and files in the change,
568 # so we can share it with helpful developers who don't use Aegis.
569 #
570
571 if change:
572     df = []
573     cmd = "aegis -list -unf -c %s cf 2>/dev/null" % change
574     for line in map(lambda x: x[:-1], os.popen(cmd, "r").readlines()):
575         a = string.split(line)
576         if a[1] == "remove":
577             if a[3][0] == '(':
578                 df.append(a[4])
579             else:
580                 df.append(a[3])
581
582     cmd = "aegis -list -terse pf 2>/dev/null"
583     pf = map(lambda x: x[:-1], os.popen(cmd, "r").readlines())
584     cmd = "aegis -list -terse cf 2>/dev/null"
585     cf = map(lambda x: x[:-1], os.popen(cmd, "r").readlines())
586     u = {}
587     for f in pf + cf:
588         u[f] = 1
589     for f in df:
590         del u[f]
591     sfiles = filter(lambda x: x[-9:] != '.aeignore' 
592                               and x[-8:] != '.consign'
593                               and x[-9:] != '.sconsign',
594                     u.keys())
595
596     if sfiles:
597         ps = "%s-src" % project
598         psv = "%s-%s" % (ps, version)
599         b_ps = os.path.join('build', ps)
600         b_psv = os.path.join('build', psv)
601
602         src_archive = os.path.join('build', 'dist', '%s.tar.gz' % psv)
603
604         for file in sfiles:
605             env.SCons_revision(os.path.join(b_ps, file), file)
606
607         b_ps_files = map(lambda x, d=b_ps: os.path.join(d, x), sfiles)
608         cmds = [
609             "rm -rf %s" % b_psv,
610             "cp -rp %s %s" % (b_ps, b_psv),
611             "find %s -name .consign -exec rm {} \\;" % b_psv,
612             "find %s -name .sconsign -exec rm {} \\;" % b_psv,
613             "tar czh -f $TARGET -C build %s" % psv,
614         ]
615
616         env.Command(src_archive, src_deps + b_ps_files, cmds)
617
618         #
619         # Unpack the archive created by the distutils into
620         # build/unpack/scons-{version}.
621         #
622         unpack_files = map(lambda x, u=unpack_dir, psv=psv:
623                                   os.path.join(u, psv, x),
624                            sfiles)
625
626         #
627         # We'd like to replace the last three lines with the following:
628         #
629         #       tar zxf %< -C $unpack_dir
630         #
631         # but that gives heartburn to Cygwin's tar, so work around it
632         # with separate zcat-tar-rm commands.
633         env.Command(unpack_files, src_archive, [
634             "rm -rf %s" % os.path.join(unpack_dir, psv),
635             "zcat $SOURCES > .temp",
636             "tar xf .temp -C %s" % unpack_dir,
637             "rm -f .temp",
638         ])
639
640         #
641         # Run setup.py in the unpacked subdirectory to "install" everything
642         # into our build/test subdirectory.  The runtest.py script will set
643         # PYTHONPATH so that the tests only look under build/test-{package},
644         # and under etc (for the testing modules TestCmd.py, TestSCons.py,
645         # and unittest.py).  This makes sure that our tests pass with what
646         # we really packaged, not because of something hanging around in
647         # the development directory.
648         #
649         # We can get away with calling setup.py using a directory path
650         # like this because we put a preamble in it that will chdir()
651         # to the directory in which setup.py exists.
652         dfiles = map(lambda x, d=test_src_arch_dir: os.path.join(d, x),
653                         dst_files)
654         ENV = env.Dictionary('ENV')
655         ENV['SCONS_LIB_DIR'] = os.path.join(unpack_dir, psv, 'src', 'engine')
656         ENV['USERNAME'] = developer
657         env.Copy(ENV = ENV).Command(dfiles, unpack_files, [
658             "rm -rf %s" % os.path.join(unpack_dir,
659                                        psv,
660                                        'build',
661                                        'scons',
662                                        'build'),
663             "rm -rf %s" % test_src_arch_dir,
664             "cd %s && python %s %s" % \
665                 (os.path.join(unpack_dir, psv),
666                  os.path.join('src', 'script', 'scons.py'),
667                  os.path.join('build', 'scons')),
668             "python %s install --prefix=%s" % (os.path.join(unpack_dir,
669                                                             psv,
670                                                             'build',
671                                                             'scons',
672                                                             'setup.py'),
673                                                test_src_arch_dir
674                                               ),
675         ])