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