]> git.rkrishnan.org Git - tahoe-lafs/zfec.git/blob - zfec/ez_setup.py
zfec: setup: copy in my latest version of ez_setup.py -- this one correctly detects...
[tahoe-lafs/zfec.git] / zfec / ez_setup.py
1 #!/usr/bin/env python
2 """Bootstrap setuptools installation
3
4 If you want to use setuptools in your package's setup.py, just include this
5 file in the same directory with it, and add this to the top of your setup.py::
6
7     from ez_setup import use_setuptools
8     use_setuptools()
9
10 If you want to require a specific version of setuptools, set a download
11 mirror, or use an alternate download directory, you can do so by supplying
12 the appropriate options to ``use_setuptools()``.
13
14 This file can also be run as a script to install or upgrade setuptools.
15 """
16 import os, sys
17 DEFAULT_VERSION = "0.6c7"
18 DEFAULT_URL     = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
19
20 md5_data = {
21     'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
22     'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
23     'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
24 }
25
26 def _validate_md5(egg_name, data):
27     if egg_name in md5_data:
28         from md5 import md5
29         digest = md5(data).hexdigest()
30         if digest != md5_data[egg_name]:
31             print >>sys.stderr, (
32                 "md5 validation of %s failed!  (Possible download problem?)"
33                 % egg_name
34             )
35             sys.exit(2)
36     return data
37
38 # The following code to parse versions is copied from pkg_resources.py so that
39 # we can parse versions without importing that module.
40 import re
41 component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
42 replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get
43
44 def _parse_version_parts(s):
45     for part in component_re.split(s):
46         part = replace(part,part)
47         if not part or part=='.':
48             continue
49         if part[:1] in '0123456789':
50             yield part.zfill(8)    # pad for numeric comparison
51         else:
52             yield '*'+part
53
54     yield '*final'  # ensure that alpha/beta/candidate are before final
55
56 def parse_version(s):
57     parts = []
58     for part in _parse_version_parts(s.lower()):
59         if part.startswith('*'):
60             if part<'*final':   # remove '-' before a prerelease tag
61                 while parts and parts[-1]=='*final-': parts.pop()
62             # remove trailing zeros from each series of numeric parts
63             while parts and parts[-1]=='00000000':
64                 parts.pop()
65         parts.append(part)
66     return tuple(parts)
67
68 def setuptools_is_new_enough(required_version):
69     """Return True if setuptools is already installed and has a version
70     number >= required_version."""
71     (cin, cout, cerr,) = os.popen3("%s -c \"import os,sys; sys.path.extend([x for x in os.listdir('.') if x.endswith('.egg')] ; import setuptools;print setuptools.__version__\"" % (sys.executable,))
72     verstr = cout.read().strip()
73     ver = parse_version(verstr)
74     return ver and ver >= parse_version(required_version)
75
76 def use_setuptools(
77     version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
78     min_version=None, download_delay=15
79 ):
80     """Automatically find/download setuptools and make it available on sys.path
81
82     `version` should be a valid setuptools version number that is available
83     as an egg for download under the `download_base` URL (which should end with
84     a '/').  `to_dir` is the directory where setuptools will be downloaded, if
85     it is not already available.  If `download_delay` is specified, it should
86     be the number of seconds that will be paused before initiating a download,
87     should one be required.  If an older version of setuptools is installed,
88     this routine will print a message to ``sys.stderr`` and raise SystemExit in
89     an attempt to abort the calling script.
90     """
91     if min_version is None:
92         min_version = version
93     if not setuptools_is_new_enough(min_version):
94         egg = download_setuptools(version, min_version, download_base, to_dir, download_delay)
95         sys.path.insert(0, egg)
96         import setuptools; setuptools.bootstrap_install_from = egg
97
98 def download_setuptools(
99     version=DEFAULT_VERSION, min_version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
100     delay = 15
101 ):
102     """Download setuptools from a specified location and return its filename
103
104     `version` should be a valid setuptools version number that is available
105     as an egg for download under the `download_base` URL (which should end
106     with a '/'). `to_dir` is the directory where the egg will be downloaded.
107     `delay` is the number of seconds to pause before an actual download attempt.
108     """
109     import urllib2, shutil
110     egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
111     url = download_base + egg_name
112     saveto = os.path.join(to_dir, egg_name)
113     src = dst = None
114     if not os.path.exists(saveto):  # Avoid repeated downloads
115         try:
116             from distutils import log
117             if delay:
118                 log.warn("""
119 ---------------------------------------------------------------------------
120 This script requires setuptools version >= %s to run (even to display
121 help).  I will attempt to download setuptools for you (from
122 %s), but
123 you may need to enable firewall access for this script first.
124 I will start the download in %d seconds.
125
126 (Note: if this machine does not have network access, please obtain the file
127
128    %s
129
130 and place it in this directory before rerunning this script.)
131 ---------------------------------------------------------------------------""",
132                     min_version, download_base, delay, url
133                 ); from time import sleep; sleep(delay)
134             log.warn("Downloading %s", url)
135             src = urllib2.urlopen(url)
136             # Read/write all in one block, so we don't create a corrupt file
137             # if the download is interrupted.
138             data = _validate_md5(egg_name, src.read())
139             dst = open(saveto,"wb"); dst.write(data)
140         finally:
141             if src: src.close()
142             if dst: dst.close()
143     return os.path.realpath(saveto)
144
145 def main(argv, version=DEFAULT_VERSION):
146     """Install or upgrade setuptools and EasyInstall"""
147
148     if setuptools_is_new_enough(version):
149         if argv:
150             from setuptools.command.easy_install import main
151             main(argv)
152         else:
153             print "Setuptools version",version,"or greater has been installed."
154             print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
155     else:
156         egg = None
157         try:
158             egg = download_setuptools(version, min_version=version, delay=0)
159             sys.path.insert(0,egg)
160             from setuptools.command.easy_install import main
161             return main(list(argv)+[egg])   # we're done here
162         finally:
163             if egg and os.path.exists(egg):
164                 os.unlink(egg)
165
166 def update_md5(filenames):
167     """Update our built-in md5 registry"""
168
169     import re
170     from md5 import md5
171
172     for name in filenames:
173         base = os.path.basename(name)
174         f = open(name,'rb')
175         md5_data[base] = md5(f.read()).hexdigest()
176         f.close()
177
178     data = ["    %r: %r,\n" % it for it in md5_data.items()]
179     data.sort()
180     repl = "".join(data)
181
182     import inspect
183     srcfile = inspect.getsourcefile(sys.modules[__name__])
184     f = open(srcfile, 'rb'); src = f.read(); f.close()
185
186     match = re.search("\nmd5_data = {\n([^}]+)}", src)
187     if not match:
188         print >>sys.stderr, "Internal error!"
189         sys.exit(2)
190
191     src = src[:match.start(1)] + repl + src[match.end(1):]
192     f = open(srcfile,'w')
193     f.write(src)
194     f.close()
195
196
197 if __name__=='__main__':
198     if '--md5update' in sys.argv:
199         sys.argv.remove('--md5update')
200         update_md5(sys.argv[1:])
201     else:
202         main(sys.argv[1:])