]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - setup.py
setup: hack the sys.argv to set poll reactor if "python ./setup.py test" in addition...
[tahoe-lafs/tahoe-lafs.git] / setup.py
1 #! /usr/bin/env python
2
3 # Allmydata Tahoe -- secure, distributed storage grid
4 #
5 # Copyright (C) 2008 Allmydata, Inc.
6 #
7 # This file is part of tahoe.
8 #
9 # See the docs/about.html file for licensing information.
10
11 import os, re, shutil, stat, subprocess, sys, zipfile
12
13 ##### sys.path management
14
15 def pylibdir(prefixdir):
16     pyver = "python%d.%d" % (sys.version_info[:2])
17     if sys.platform == "win32":
18         return os.path.join(prefixdir, "Lib", "site-packages")
19     else:
20         return os.path.join(prefixdir, "lib", pyver, "site-packages")
21
22 basedir = os.path.dirname(os.path.abspath(__file__))
23 supportlib = pylibdir(os.path.join(basedir, "support"))
24
25
26 for i in range(len(sys.argv)):
27     arg = sys.argv[i]
28     prefixdir = None
29     if arg.startswith("--prefix="):
30         prefixdir = arg[len("--prefix="):]
31     if arg == "--prefix":
32         if len(sys.argv) > i+1:
33             prefixdir = sys.argv[i+1]
34
35     if prefixdir:
36         libdir = pylibdir(prefixdir)
37         try:
38             os.makedirs(libdir)
39         except EnvironmentError, le:
40             # Okay, maybe the dir was already there.
41             pass
42         sys.path.append(libdir)
43         pp = os.environ.get('PYTHONPATH','').split(os.pathsep)
44         pp.append(libdir)
45         os.environ['PYTHONPATH'] = os.pathsep.join(pp)
46
47     if arg.startswith("develop"):
48         if sys.platform == "linux2":
49             # workaround for tahoe #229 / setuptools #17, on debian
50             sys.argv.extend(["--site-dirs", "/var/lib/python-support/python%d.%d" % (sys.version_info[:2])])
51         elif sys.platform == "darwin":
52             # this probably only applies to leopard 10.5, possibly only 10.5.5
53             sd = "/System/Library/Frameworks/Python.framework/Versions/%d.%d/Extras/lib/python" % (sys.version_info[:2])
54             sys.argv.extend(["--site-dirs", sd])
55
56 try:
57     from ez_setup import use_setuptools
58 except ImportError:
59     pass
60 else:
61     # This invokes our own customized version of ez_setup.py to make sure that
62     # setuptools >= v0.6c8 (a.k.a. v0.6-final) is installed.
63
64     # setuptools < v0.6c8 doesn't handle eggs which get installed into the CWD
65     # as a result of being transitively depended on in a setup_requires, but
66     # then are needed for the installed code to run, i.e. in an
67     # install_requires.
68     use_setuptools(download_delay=0, min_version="0.6c10dev")
69
70 from setuptools import find_packages, setup
71 from setuptools.command import sdist
72 from distutils.core import Command
73 from pkg_resources import require
74
75 # Make the dependency-version-requirement, which is used by the Makefile at
76 # build-time, also available to the app at runtime:
77 import shutil
78 shutil.copyfile("_auto_deps.py", os.path.join("src", "allmydata", "_auto_deps.py"))
79
80 trove_classifiers=[
81     "Development Status :: 5 - Production/Stable",
82     "Environment :: Console",
83     "Environment :: Web Environment",
84     "License :: OSI Approved :: GNU General Public License (GPL)",
85     "License :: DFSG approved",
86     "License :: Other/Proprietary License",
87     "Intended Audience :: Developers",
88     "Intended Audience :: End Users/Desktop",
89     "Intended Audience :: System Administrators",
90     "Operating System :: Microsoft",
91     "Operating System :: Microsoft :: Windows",
92     "Operating System :: Microsoft :: Windows :: Windows NT/2000",
93     "Operating System :: Unix",
94     "Operating System :: POSIX :: Linux",
95     "Operating System :: POSIX",
96     "Operating System :: MacOS :: MacOS X",
97     "Operating System :: OS Independent",
98     "Natural Language :: English",
99     "Programming Language :: C",
100     "Programming Language :: Python",
101     "Programming Language :: Python :: 2",
102     "Programming Language :: Python :: 2.4",
103     "Programming Language :: Python :: 2.5",
104     "Topic :: Utilities",
105     "Topic :: System :: Systems Administration",
106     "Topic :: System :: Filesystems",
107     "Topic :: System :: Distributed Computing",
108     "Topic :: Software Development :: Libraries",
109     "Topic :: Communications :: Usenet News",
110     "Topic :: System :: Archiving :: Backup",
111     "Topic :: System :: Archiving :: Mirroring",
112     "Topic :: System :: Archiving",
113     ]
114
115
116 VERSIONFILE = "src/allmydata/_version.py"
117 verstr = "unknown"
118 try:
119     verstrline = open(VERSIONFILE, "rt").read()
120 except EnvironmentError:
121     pass # Okay, there is no version file.
122 else:
123     VSRE = r"^verstr = ['\"]([^'\"]*)['\"]"
124     mo = re.search(VSRE, verstrline, re.M)
125     if mo:
126         verstr = mo.group(1)
127     else:
128         print "unable to find version in %s" % (VERSIONFILE,)
129         raise RuntimeError("if %s.py exists, it is required to be well-formed" % (VERSIONFILE,))
130
131 LONG_DESCRIPTION=\
132 """Welcome to the Tahoe project, a secure, decentralized, fault-tolerant
133 filesystem.  All of the source code is available under a Free Software, Open
134 Source licence.
135
136 This filesystem is encrypted and spread over multiple peers in such a way that
137 it remains available even when some of the peers are unavailable,
138 malfunctioning, or malicious."""
139
140
141 setup_requires = []
142
143 # Nevow requires Twisted to setup, but doesn't declare that requirement in a way that enables
144 # setuptools to satisfy that requirement before Nevow's setup.py tried to "import twisted".
145 # Fortunately we require setuptools_trial to setup and setuptools_trial requires Twisted to
146 # install, so hopefully everything will work out until the Nevow issue is fixed:
147 # http://divmod.org/trac/ticket/2629
148 # setuptools_trial is needed if you want "./setup.py trial" or "./setup.py test" to execute the
149 # tests (and in order to make sure Twisted is installed early enough -- see the paragraph
150 # above).
151 # http://pypi.python.org/pypi/setuptools_trial
152 setup_requires.extend(['setuptools_trial'])
153
154 # darcsver is needed if you want "./setup.py darcsver" to write a new version stamp in
155 # src/allmydata/_version.py, with a version number derived from darcs history.
156 # http://pypi.python.org/pypi/darcsver
157 setup_requires.append('darcsver >= 1.1.5')
158
159 if 'trial' in sys.argv[1:] or 'test' in sys.argv[1:]:
160     # Cygwin requires the poll reactor to work at all.  Linux requires the poll reactor to avoid
161     # bug #402 (twisted bug #3218).  In general, the poll reactor is better than the select
162     # reactor, but it is not available on all platforms.  According to exarkun on IRC, it is
163     # available but buggy on some versions of Mac OS X, so just because you can install it
164     # doesn't mean we want to use it on every platform.
165     if sys.platform in ("linux2", "cygwin"):
166         if not [a for a in sys.argv if a.startswith("--reactor")]:
167             sys.argv.append("--reactor=poll")
168
169 # setuptools_darcs is required to produce complete distributions (such as with
170 # "sdist" or "bdist_egg"), unless there is a PKG-INFO file present which shows
171 # that this is itself a source distribution.
172 # http://pypi.python.org/pypi/setuptools_darcs
173 if not os.path.exists('PKG-INFO'):
174     setup_requires.append('setuptools_darcs >= 1.1.0')
175
176 class ShowSupportLib(Command):
177     user_options = []
178     def initialize_options(self):
179         pass
180     def finalize_options(self):
181         pass
182     def run(self):
183         # TODO: --quiet suppresses the 'running show_supportlib' message.
184         # Find a way to do this all the time.
185         print supportlib # TODO windowsy
186
187 class ShowPythonPath(Command):
188     user_options = []
189     def initialize_options(self):
190         pass
191     def finalize_options(self):
192         pass
193     def run(self):
194         # TODO: --quiet suppresses the 'running show_supportlib' message.
195         # Find a way to do this all the time.
196         print "PYTHONPATH=%s" % os.environ.get("PYTHONPATH", '')
197
198 class RunWithPythonPath(Command):
199     description = "Run a subcommand with PYTHONPATH set appropriately"
200
201     user_options = [ ("python", "p",
202                       "Treat command string as arguments to a python executable"),
203                      ("command=", "c", "Command to be run"),
204                      ("directory=", "d", "Directory to run the command in"),
205                      ]
206     boolean_options = ["python"]
207
208     def initialize_options(self):
209         self.command = None
210         self.python = False
211         self.directory = None
212     def finalize_options(self):
213         pass
214     def run(self):
215         oldpp = os.environ.get("PYTHONPATH", "").split(os.pathsep)
216         if oldpp == [""]:
217             # grr silly split() behavior
218             oldpp = []
219         os.environ['PYTHONPATH'] = os.pathsep.join(oldpp + [supportlib,])
220
221         # We must require the command to be safe to split on
222         # whitespace, and have --python and --directory to make it
223         # easier to achieve this.
224
225         command = []
226         if self.python:
227             command.append(sys.executable)
228         if self.command:
229             command.extend(self.command.split())
230         if not command:
231             raise RuntimeError("The --command argument is mandatory")
232         if self.directory:
233             os.chdir(self.directory)
234         if self.verbose:
235             print "command =", " ".join(command)
236         rc = subprocess.call(command)
237         sys.exit(rc)
238
239 class CheckAutoDeps(Command):
240     user_options = []
241     def initialize_options(self):
242         pass
243     def finalize_options(self):
244         pass
245     def run(self):
246         import _auto_deps
247         _auto_deps.require_auto_deps()
248
249
250 class BuildTahoe(Command):
251     user_options = []
252     def initialize_options(self):
253         pass
254     def finalize_options(self):
255         pass
256     def run(self):
257         # chmod +x bin/tahoe
258         bin_tahoe = os.path.join("bin", "tahoe")
259         old_mode = stat.S_IMODE(os.stat(bin_tahoe)[stat.ST_MODE])
260         new_mode = old_mode | (stat.S_IXUSR | stat.S_IRUSR |
261                                stat.S_IXGRP | stat.S_IRGRP |
262                                stat.S_IXOTH | stat.S_IROTH )
263         os.chmod(bin_tahoe, new_mode)
264
265         # On Windows, create the 'tahoe-script.py' file based on the 'tahoe'
266         # executable script under the 'bin' directory so that the tahoe.exe
267         # will work correctly.  The 'tahoe-script.py' file is exactly the same
268         # as the 'tahoe' script except that we need to update the she-bang
269         # line.  The tahoe.exe will be copied from the setuptools egg's cli.exe
270         # and this will work from a zip-safe and non-zip-safe setuptools egg.
271         if sys.platform == "win32":
272             setuptools_egg = require("setuptools")[0].location
273             if os.path.isfile(setuptools_egg):
274                 z = zipfile.ZipFile(setuptools_egg, 'r')
275                 for filename in z.namelist():
276                     if 'cli.exe' in filename:
277                         cli_exe = z.read(filename)
278             else:
279                 cli_exe = os.path.join(setuptools_egg, 'setuptools', 'cli.exe')
280             tahoe_exe = os.path.join("bin", "tahoe.exe")
281             if os.path.isfile(setuptools_egg):
282                 f = open(tahoe_exe, 'wb')
283                 f.write(cli_exe)
284                 f.close()
285             else:
286                 shutil.copy(cli_exe, tahoe_exe)
287             f = open(bin_tahoe, "r")
288             script_lines = f.readlines()
289             f.close()
290             script_lines[0] = "#!%s\n" % sys.executable
291             tahoe_script = os.path.join("bin", "tahoe-script.py")
292             f = open(tahoe_script, "w")
293             for line in script_lines:
294                 f.write(line)
295             f.close()
296
297         command = [sys.executable, "setup.py", "develop",
298             "--prefix=support"]
299         print "Command:", " ".join(command)
300         rc = subprocess.call(command)
301         if rc < 0:
302             print >>sys.stderr, "'setup.py develop' terminated by signal", -rc
303             sys.exit(1)
304         elif rc > 0:
305             print >>sys.stderr, "'setup.py develop' exited with rc", rc
306             sys.exit(rc)
307
308 class MySdist(sdist.sdist):
309     """ A hook in the sdist command so that we can determine whether this the
310     tarball should be 'SUMO' or not, i.e. whether or not to include the
311     external dependency tarballs. Note that we always include
312     misc/dependencies/* in the tarball; --sumo controls whether tahoe-deps/*
313     is included as well.
314     """
315
316     user_options = sdist.sdist.user_options + \
317         [('sumo', 's',
318           "create a 'sumo' sdist which includes the contents of tahoe-deps/*"),
319          ]
320     boolean_options = ['sumo']
321
322     def initialize_options(self):
323         sdist.sdist.initialize_options(self)
324         self.sumo = False
325
326     def make_distribution(self):
327         # add our extra files to the list just before building the
328         # tarball/zipfile. We override make_distribution() instead of run()
329         # because setuptools.command.sdist.run() does not lend itself to
330         # easy/robust subclassing (the code we need to add goes right smack
331         # in the middle of a 12-line method). If this were the distutils
332         # version, we'd override get_file_list().
333
334         if self.sumo:
335             # If '--sumo' was specified, include tahoe-deps/* in the sdist.
336             # We assume that the user has fetched the tahoe-deps.tar.gz
337             # tarball and unpacked it already.
338             self.filelist.extend([os.path.join("tahoe-deps", fn)
339                                   for fn in os.listdir("tahoe-deps")])
340             # In addition, we want the tarball/zipfile to have -SUMO in the
341             # name, and the unpacked directory to have -SUMO too. The easiest
342             # way to do this is to patch self.distribution and override the
343             # get_fullname() method. (an alternative is to modify
344             # self.distribution.metadata.version, but that also affects the
345             # contents of PKG-INFO).
346             fullname = self.distribution.get_fullname()
347             def get_fullname():
348                 return fullname + "-SUMO"
349             self.distribution.get_fullname = get_fullname
350
351         return sdist.sdist.make_distribution(self)
352
353 # Tahoe's dependencies are managed by the find_links= entry in setup.cfg and
354 # the _auto_deps.install_requires list, which is used in the call to setup()
355 # at the end of this file
356 from _auto_deps import install_requires
357
358 setup(name='allmydata-tahoe',
359       version=verstr,
360       description='secure, decentralized, fault-tolerant filesystem',
361       long_description=LONG_DESCRIPTION,
362       author='the allmydata.org Tahoe project',
363       author_email='tahoe-dev@allmydata.org',
364       url='http://allmydata.org/',
365       license='GNU GPL',
366       cmdclass={"show_supportlib": ShowSupportLib,
367                 "show_pythonpath": ShowPythonPath,
368                 "run_with_pythonpath": RunWithPythonPath,
369                 "check_auto_deps": CheckAutoDeps,
370                 "build_tahoe": BuildTahoe,
371                 "sdist": MySdist,
372                 },
373       package_dir = {'':'src'},
374       packages=find_packages("src"),
375       classifiers=trove_classifiers,
376       test_suite="allmydata.test",
377       install_requires=install_requires,
378       include_package_data=True,
379       setup_requires=setup_requires,
380       entry_points = { 'console_scripts': [ 'tahoe = allmydata.scripts.runner:run' ] },
381       zip_safe=False, # We prefer unzipped for easier access.
382       )