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