]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - setup.py
setup.py: look for a tag named after APPNAME, not necessarily "allmydata-tahoe"....
[tahoe-lafs/tahoe-lafs.git] / setup.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import sys; assert sys.version_info < (3,), ur"Tahoe-LAFS does not run under Python 3. Please use a version of Python between 2.6 and 2.7.x inclusive."
4
5 # Tahoe-LAFS -- secure, distributed storage grid
6 #
7 # Copyright © 2006-2012 The Tahoe-LAFS Software Foundation
8 #
9 # This file is part of Tahoe-LAFS.
10 #
11 # See the docs/about.rst file for licensing information.
12
13 import os, stat, subprocess, re
14
15 ##### sys.path management
16
17 def pylibdir(prefixdir):
18     pyver = "python%d.%d" % (sys.version_info[:2])
19     if sys.platform == "win32":
20         return os.path.join(prefixdir, "Lib", "site-packages")
21     else:
22         return os.path.join(prefixdir, "lib", pyver, "site-packages")
23
24 basedir = os.path.dirname(os.path.abspath(__file__))
25 supportlib = pylibdir(os.path.join(basedir, "support"))
26
27 # locate our version number
28
29 def read_version_py(infname):
30     try:
31         verstrline = open(infname, "rt").read()
32     except EnvironmentError:
33         return None
34     else:
35         VSRE = r"^verstr = ['\"]([^'\"]*)['\"]"
36         mo = re.search(VSRE, verstrline, re.M)
37         if mo:
38             return mo.group(1)
39
40 VERSION_PY_FILENAME = 'src/allmydata/_version.py'
41 version = read_version_py(VERSION_PY_FILENAME)
42
43 APPNAME='allmydata-tahoe'
44 APPNAMEFILE = os.path.join('src', 'allmydata', '_appname.py')
45 APPNAMEFILESTR = "__appname__ = '%s'" % (APPNAME,)
46 try:
47     curappnamefilestr = open(APPNAMEFILE, 'rU').read()
48 except EnvironmentError:
49     # No file, or unreadable or something, okay then let's try to write one.
50     open(APPNAMEFILE, "w").write(APPNAMEFILESTR)
51 else:
52     if curappnamefilestr.strip() != APPNAMEFILESTR:
53         print("Error -- this setup.py file is configured with the 'application name' to be '%s', but there is already a file in place in '%s' which contains the contents '%s'.  If the file is wrong, please remove it and setup.py will regenerate it and write '%s' into it." % (APPNAME, APPNAMEFILE, curappnamefilestr, APPNAMEFILESTR))
54         sys.exit(-1)
55
56 # setuptools/zetuptoolz looks in __main__.__requires__ for a list of
57 # requirements. When running "python setup.py test", __main__ is
58 # setup.py, so we put the list here so that the requirements will be
59 # available for tests:
60
61 # Tahoe's dependencies are managed by the find_links= entry in setup.cfg and
62 # the _auto_deps.install_requires list, which is used in the call to setup()
63 # below.
64 adglobals = {}
65 execfile('src/allmydata/_auto_deps.py', adglobals)
66 install_requires = adglobals['install_requires']
67
68 if len(sys.argv) > 1 and sys.argv[1] == '--fakedependency':
69     del sys.argv[1]
70     install_requires += ["fakedependency >= 1.0.0"]
71
72 __requires__ = install_requires[:]
73
74 egg = os.path.realpath('setuptools-0.6c16dev5.egg')
75 sys.path.insert(0, egg)
76 import setuptools; setuptools.bootstrap_install_from = egg
77
78 from setuptools import setup
79 from setuptools.command import sdist
80 from setuptools import Command
81
82 trove_classifiers=[
83     "Development Status :: 5 - Production/Stable",
84     "Environment :: Console",
85     "Environment :: Web Environment",
86     "License :: OSI Approved :: GNU General Public License (GPL)",
87     "License :: DFSG approved",
88     "License :: Other/Proprietary License",
89     "Intended Audience :: Developers",
90     "Intended Audience :: End Users/Desktop",
91     "Intended Audience :: System Administrators",
92     "Operating System :: Microsoft",
93     "Operating System :: Microsoft :: Windows",
94     "Operating System :: Unix",
95     "Operating System :: POSIX :: Linux",
96     "Operating System :: POSIX",
97     "Operating System :: MacOS :: MacOS X",
98     "Operating System :: OS Independent",
99     "Natural Language :: English",
100     "Programming Language :: C",
101     "Programming Language :: Python",
102     "Programming Language :: Python :: 2",
103     "Programming Language :: Python :: 2.6",
104     "Programming Language :: Python :: 2.7",
105     "Topic :: Utilities",
106     "Topic :: System :: Systems Administration",
107     "Topic :: System :: Filesystems",
108     "Topic :: System :: Distributed Computing",
109     "Topic :: Software Development :: Libraries",
110     "Topic :: System :: Archiving :: Backup",
111     "Topic :: System :: Archiving :: Mirroring",
112     "Topic :: System :: Archiving",
113     ]
114
115
116 setup_requires = []
117
118 # Nevow imports itself when building, which causes Twisted and zope.interface
119 # to be imported. We need to make sure that the versions of Twisted and
120 # zope.interface used at build time satisfy Nevow's requirements. If not
121 # then there are two problems:
122 #  - prior to Nevow v0.9.33, Nevow didn't declare its dependency on Twisted
123 #    in a way that enabled setuptools to satisfy that requirement at
124 #    build time.
125 #  - some versions of zope.interface, e.g. v3.6.4, are incompatible with
126 #    Nevow, and we need to avoid those both at build and run-time.
127 #
128 # This only matters when compatible versions of Twisted and zope.interface
129 # are not already installed. Retire this hack when
130 # https://bugs.launchpad.net/nevow/+bug/812537 has been fixed.
131 setup_requires += [req for req in install_requires if req.startswith('Twisted') or req.startswith('zope.interface')]
132
133 # We no longer have any requirements specific to tests.
134 tests_require=[]
135
136
137 class Trial(Command):
138     description = "run trial (use 'bin%stahoe debug trial' for the full set of trial options)" % (os.sep,)
139     # This is just a subset of the most useful options, for compatibility.
140     user_options = [ ("no-rterrors", None, "Don't print out tracebacks as they occur."),
141                      ("rterrors", "e", "Print out tracebacks as they occur (default, so ignored)."),
142                      ("until-failure", "u", "Repeat a test (specified by -s) until it fails."),
143                      ("reporter=", None, "The reporter to use for this test run."),
144                      ("suite=", "s", "Specify the test suite."),
145                      ("quiet", None, "Don't display version numbers and paths of Tahoe dependencies."),
146                      ("coverage", "c", "Collect branch coverage information."),
147                    ]
148
149     def initialize_options(self):
150         self.rterrors = False
151         self.no_rterrors = False
152         self.until_failure = False
153         self.reporter = None
154         self.suite = "allmydata"
155         self.quiet = False
156         self.coverage = False
157
158     def finalize_options(self):
159         pass
160
161     def run(self):
162         args = [sys.executable, os.path.join('bin', 'tahoe')]
163
164         if self.coverage:
165             from errno import ENOENT
166             coverage_cmd = 'coverage'
167             try:
168                 subprocess.call([coverage_cmd, 'help'])
169             except OSError as e:
170                 if e.errno != ENOENT:
171                     raise
172                 coverage_cmd = 'python-coverage'
173                 try:
174                     rc = subprocess.call([coverage_cmd, 'help'])
175                 except OSError as e:
176                     if e.errno != ENOENT:
177                         raise
178                     print >>sys.stderr
179                     print >>sys.stderr, "Couldn't find the command 'coverage' nor 'python-coverage'."
180                     print >>sys.stderr, "coverage can be installed using 'pip install coverage', or on Debian-based systems, 'apt-get install python-coverage'."
181                     sys.exit(1)
182
183             args += ['@' + coverage_cmd, 'run', '--branch', '--source=src/allmydata', '@tahoe']
184
185         if not self.quiet:
186             args.append('--version-and-path')
187         args += ['debug', 'trial']
188         if self.rterrors and self.no_rterrors:
189             raise AssertionError("--rterrors and --no-rterrors conflict.")
190         if not self.no_rterrors:
191             args.append('--rterrors')
192         if self.until_failure:
193             args.append('--until-failure')
194         if self.reporter:
195             args.append('--reporter=' + self.reporter)
196         if self.suite:
197             args.append(self.suite)
198         rc = subprocess.call(args)
199         sys.exit(rc)
200
201
202 class MakeExecutable(Command):
203     description = "make the 'bin%stahoe' scripts" % (os.sep,)
204     user_options = []
205
206     def initialize_options(self):
207         pass
208     def finalize_options(self):
209         pass
210     def run(self):
211         bin_tahoe_template = os.path.join("bin", "tahoe-script.template")
212
213         # tahoe.pyscript is really only necessary for Windows, but we also
214         # create it on Unix for consistency.
215         script_names = ["tahoe.pyscript", "tahoe"]
216
217         # Create the tahoe script file under the 'bin' directory. This
218         # file is exactly the same as the 'tahoe-script.template' script
219         # except that the shebang line is rewritten to use our sys.executable
220         # for the interpreter.
221         f = open(bin_tahoe_template, "rU")
222         script_lines = f.readlines()
223         f.close()
224         script_lines[0] = '#!%s\n' % (sys.executable,)
225         for script_name in script_names:
226             tahoe_script = os.path.join("bin", script_name)
227             try:
228                 os.remove(tahoe_script)
229             except Exception:
230                 if os.path.exists(tahoe_script):
231                    raise
232             f = open(tahoe_script, "wb")
233             for line in script_lines:
234                 f.write(line)
235             f.close()
236
237         # chmod +x
238         unix_script = os.path.join("bin", "tahoe")
239         old_mode = stat.S_IMODE(os.stat(unix_script)[stat.ST_MODE])
240         new_mode = old_mode | (stat.S_IXUSR | stat.S_IRUSR |
241                                stat.S_IXGRP | stat.S_IRGRP |
242                                stat.S_IXOTH | stat.S_IROTH )
243         os.chmod(unix_script, new_mode)
244
245         old_tahoe_exe = os.path.join("bin", "tahoe.exe")
246         try:
247             os.remove(old_tahoe_exe)
248         except Exception:
249             if os.path.exists(old_tahoe_exe):
250                 raise
251
252
253 GIT_VERSION_BODY = '''
254 # This _version.py is generated from git metadata by the tahoe setup.py.
255
256 __pkgname__ = %(pkgname)r
257 real_version = %(version)r
258 full_version = %(full)r
259 branch = %(branch)r
260 verstr = %(normalized)r
261 __version__ = verstr
262 '''
263
264 def run_command(args, cwd=None):
265     try:
266         # remember shell=False, so use git.cmd on windows, not just git
267         p = subprocess.Popen(args, stdout=subprocess.PIPE, cwd=cwd)
268     except EnvironmentError as e:  # if this gives a SyntaxError, note that Tahoe-LAFS requires Python 2.6+
269         print("Warning: unable to run %r." % (" ".join(args),))
270         print(e)
271         return None
272     stdout = p.communicate()[0].strip()
273     if p.returncode != 0:
274         print("Warning: %r returned error code %r." % (" ".join(args), p.returncode))
275         return None
276     return stdout
277
278
279 def versions_from_git(tag_prefix):
280     # This runs 'git' from the directory that contains this file. That either
281     # means someone ran a setup.py command (and this code is in
282     # versioneer.py, thus the containing directory is the root of the source
283     # tree), or someone ran a project-specific entry point (and this code is
284     # in _version.py, thus the containing directory is somewhere deeper in
285     # the source tree). This only gets called if the git-archive 'subst'
286     # variables were *not* expanded, and _version.py hasn't already been
287     # rewritten with a short version string, meaning we're inside a checked
288     # out source tree.
289
290     # versions_from_git (as copied from python-versioneer) returns strings
291     # like "1.9.0-25-gb73aba9-dirty", which means we're in a tree with
292     # uncommited changes (-dirty), the latest checkin is revision b73aba9,
293     # the most recent tag was 1.9.0, and b73aba9 has 25 commits that weren't
294     # in 1.9.0 . The narrow-minded NormalizedVersion parser that takes our
295     # output (meant to enable sorting of version strings) refuses most of
296     # that. Tahoe uses a function named suggest_normalized_version() that can
297     # handle "1.9.0.post25", so dumb down our output to match.
298
299     try:
300         source_dir = os.path.dirname(os.path.abspath(__file__))
301     except NameError as e:
302         # some py2exe/bbfreeze/non-CPython implementations don't do __file__
303         print("Warning: unable to find version because we could not obtain the source directory.")
304         print(e)
305         return {}
306     GIT = "git"
307     if sys.platform == "win32":
308         GIT = "git.cmd"
309     stdout = run_command([GIT, "describe", "--tags", "--dirty", "--always"],
310                          cwd=source_dir)
311     if stdout is None:
312         # run_command already complained.
313         return {}
314     if not stdout.startswith(tag_prefix):
315         print("Warning: tag %r doesn't start with prefix %r." % (stdout, tag_prefix))
316         return {}
317     version = stdout[len(tag_prefix):]
318     pieces = version.split("-")
319     if len(pieces) == 1:
320         normalized_version = pieces[0]
321     else:
322         normalized_version = "%s.post%s" % (pieces[0], pieces[1])
323
324     stdout = run_command([GIT, "rev-parse", "HEAD"], cwd=source_dir)
325     if stdout is None:
326         # run_command already complained.
327         return {}
328     full = stdout.strip()
329     if version.endswith("-dirty"):
330         full += "-dirty"
331         normalized_version += ".dev0"
332
333     # Thanks to Jistanidiot at <http://stackoverflow.com/questions/6245570/get-current-branch-name>.
334     stdout = run_command([GIT, "rev-parse", "--abbrev-ref", "HEAD"], cwd=source_dir)
335     branch = (stdout or "unknown").strip()
336
337     return {"version": version, "normalized": normalized_version, "full": full, "branch": branch}
338
339 # setup.cfg has an [aliases] section which runs "update_version" before many
340 # commands (like "build" and "sdist") that need to know our package version
341 # ahead of time. If you add different commands (or if we forgot some), you
342 # may need to add it to setup.cfg and configure it to run update_version
343 # before your command.
344
345 class UpdateVersion(Command):
346     description = "update _version.py from revision-control metadata"
347     user_options = []
348
349     def initialize_options(self):
350         pass
351     def finalize_options(self):
352         pass
353     def run(self):
354         global version
355         verstr = version
356         if os.path.isdir(os.path.join(basedir, ".git")):
357             verstr = self.try_from_git()
358
359         if verstr:
360             self.distribution.metadata.version = verstr
361         else:
362             print("""\
363 ********************************************************************
364 Warning: no version information found. This may cause tests to fail.
365 ********************************************************************
366 """)
367
368     def try_from_git(self):
369         # If we change APPNAME, the release tag names should also change from then on.
370         versions = versions_from_git(APPNAME + '-')
371         if versions:
372             f = open(VERSION_PY_FILENAME, "wb")
373             f.write(GIT_VERSION_BODY %
374                     { "pkgname": self.distribution.get_name(),
375                       "version": versions["version"],
376                       "normalized": versions["normalized"],
377                       "full": versions["full"],
378                       "branch": versions["branch"],
379                     })
380             f.close()
381             print("Wrote normalized version %r into '%s'" % (versions["normalized"], VERSION_PY_FILENAME))
382
383         return versions.get("normalized", None)
384
385
386 class MySdist(sdist.sdist):
387     """ A hook in the sdist command so that we can determine whether this the
388     tarball should be 'SUMO' or not, i.e. whether or not to include the
389     external dependency tarballs. Note that we always include
390     misc/dependencies/* in the tarball; --sumo controls whether tahoe-deps/*
391     is included as well.
392     """
393
394     user_options = sdist.sdist.user_options + \
395         [('sumo', 's',
396           "create a 'sumo' sdist which includes the contents of tahoe-deps/*"),
397          ]
398     boolean_options = ['sumo']
399
400     def initialize_options(self):
401         sdist.sdist.initialize_options(self)
402         self.sumo = False
403
404     def make_distribution(self):
405         # add our extra files to the list just before building the
406         # tarball/zipfile. We override make_distribution() instead of run()
407         # because setuptools.command.sdist.run() does not lend itself to
408         # easy/robust subclassing (the code we need to add goes right smack
409         # in the middle of a 12-line method). If this were the distutils
410         # version, we'd override get_file_list().
411
412         if self.sumo:
413             # If '--sumo' was specified, include tahoe-deps/* in the sdist.
414             # We assume that the user has fetched the tahoe-deps.tar.gz
415             # tarball and unpacked it already.
416             self.filelist.extend([os.path.join("tahoe-deps", fn)
417                                   for fn in os.listdir("tahoe-deps")])
418             # In addition, we want the tarball/zipfile to have -SUMO in the
419             # name, and the unpacked directory to have -SUMO too. The easiest
420             # way to do this is to patch self.distribution and override the
421             # get_fullname() method. (an alternative is to modify
422             # self.distribution.metadata.version, but that also affects the
423             # contents of PKG-INFO).
424             fullname = self.distribution.get_fullname()
425             def get_fullname():
426                 return fullname + "-SUMO"
427             self.distribution.get_fullname = get_fullname
428
429         try:
430             old_mask = os.umask(int("022", 8))
431             return sdist.sdist.make_distribution(self)
432         finally:
433             os.umask(old_mask)
434
435
436 setup_args = {}
437 if version:
438     setup_args["version"] = version
439
440 setup(name=APPNAME,
441       description='secure, decentralized, fault-tolerant filesystem',
442       long_description=open('README.rst', 'rU').read(),
443       author='the Tahoe-LAFS project',
444       author_email='tahoe-dev@tahoe-lafs.org',
445       url='https://tahoe-lafs.org/',
446       license='GNU GPL', # see README.rst -- there is an alternative licence
447       cmdclass={"trial": Trial,
448                 "make_executable": MakeExecutable,
449                 "update_version": UpdateVersion,
450                 "sdist": MySdist,
451                 },
452       package_dir = {'':'src'},
453       packages=['allmydata',
454                 'allmydata.frontends',
455                 'allmydata.immutable',
456                 'allmydata.immutable.downloader',
457                 'allmydata.introducer',
458                 'allmydata.mutable',
459                 'allmydata.scripts',
460                 'allmydata.storage',
461                 'allmydata.test',
462                 'allmydata.util',
463                 'allmydata.web',
464                 'allmydata.windows',
465                 'buildtest'],
466       classifiers=trove_classifiers,
467       test_suite="allmydata.test",
468       install_requires=install_requires,
469       tests_require=tests_require,
470       package_data={"allmydata.web": ["*.xhtml",
471                                       "static/*.js", "static/*.png", "static/*.css",
472                                       "static/img/*.png",
473                                       "static/css/*.css",
474                                       ]
475                     },
476       setup_requires=setup_requires,
477       entry_points = { 'console_scripts': [ 'tahoe = allmydata.scripts.runner:run' ] },
478       zip_safe=False, # We prefer unzipped for easier access.
479       **setup_args
480       )