aboutsummaryrefslogtreecommitdiffstats
path: root/easy_install.py
blob: 24f33a5968e8a0fdc53539864743348c1db6c58b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!python
"""\

Easy Install
------------

A tool for doing automatic download/extract/build of distutils-based Python
packages.  For detailed documentation, see the accompanying EasyInstall.txt
file, or visit the `EasyInstall home page`__.

__ http://peak.telecommunity.com/DevCenter/EasyInstall

"""

import sys, os.path, zipimport, shutil, tempfile

from setuptools import Command
from setuptools.sandbox import run_setup
from distutils.sysconfig import get_python_lib
from distutils.errors import DistutilsArgError
from setuptools.archive_util import unpack_archive
from setuptools.package_index import PackageIndex
from pkg_resources import *


def samefile(p1,p2):
    if hasattr(os.path,'samefile') and (
        os.path.exists(p1) and os.path.exists(p2)
    ):
        return os.path.samefile(p1,p2)
    return (
        os.path.normpath(os.path.normcase(p1)) ==
        os.path.normpath(os.path.normcase(p2))
    )







class easy_install(Command):
    """Manage a download/build/install process"""

    description = "Find/get/install Python packages"
    command_consumes_arguments = True
    user_options = [
        ("zip-ok", "z", "install package as a zipfile"),
        ("multi-version", "m", "make apps have to require() a version"),
        ("install-dir=", "d", "install package to DIR"),
        ("script-dir=", "s", "install scripts to DIR"),
        ("exclude-scripts", "x", "Don't install scripts"),
        ("index-url=", "i", "base URL of Python Package Index"),
        ("find-links=", "f", "additional URL(s) to search for packages"),
        ("build-directory=", "b",
            "download/extract/build in DIR; keep the results"),
    ]

    boolean_options = [ 'zip-ok', 'multi-version', 'exclude-scripts' ]
    create_index = PackageIndex
    
    def initialize_options(self):
        self.zip_ok = None
        self.multi_version = None
        self.install_dir = self.script_dir = self.exclude_scripts = None
        self.index_url = None
        self.find_links = None
        self.build_directory = None
        self.args = None
        
        # Options not specifiable via command line
        self.package_index = None
        self.pth_file = None

    def alloc_tmp(self):
        if self.build_directory is None:
            return tempfile.mkdtemp(prefix="easy_install-")
        tmpdir = os.path.realpath(self.build_directory)
        if not os.path.isdir(tmpdir):
            os.makedirs(tmpdir)
        return tmpdir
        
    def finalize_options(self):
        # If a non-default installation directory was specified, default the
        # script directory to match it.
        if self.script_dir is None:
            self.script_dir = self.install_dir

        # Let install_dir get set by install_lib command, which in turn
        # gets its info from the install command, and takes into account
        # --prefix and --home and all that other crud.
        self.set_undefined_options('install_lib',
            ('install_dir','install_dir')
        )         
        # Likewise, set default script_dir from 'install_scripts.install_dir'
        self.set_undefined_options('install_scripts',
            ('install_dir', 'script_dir')
        )

        site_packages = get_python_lib()       
        instdir = self.install_dir

        if instdir is None or samefile(site_packages,instdir):
            instdir = site_packages
            if self.pth_file is None:
                self.pth_file = PthDistributions(
                    os.path.join(instdir,'easy-install.pth')
                )
            self.install_dir = instdir    

        elif self.multi_version is None:
            self.multi_version = True

        elif not self.multi_version:
            # explicit false set from Python code; raise an error
            raise DistutilsArgError(
                "Can't do single-version installs outside site-packages"
            )

        self.index_url = self.index_url or "http://www.python.org/pypi"
        if self.package_index is None:
            self.package_index = self.create_index(self.index_url)

        if self.find_links is not None:
            if isinstance(self.find_links, basestring):
                self.find_links = self.find_links.split()
            for link in self.find_links:
                self.package_index.scan_url(link)

        if not self.args:
            raise DistutilsArgError(
                "No urls, filenames, or requirements specified (see --help)")
        elif len(self.args)>1 and self.build_directory is not None:
            raise DistutilsArgError(
                "Build directory can only be set when using one URL"   
            )

    def run(self):
        for spec in self.args:
            self.easy_install(spec)


    def easy_install(self, spec):       
        tmpdir = self.alloc_tmp()
        try:
            download = self.package_index.download(spec, tmpdir)
            if download is None:
                raise RuntimeError(
                    "Could not find distribution for %r" % spec
                )

            print "Processing", os.path.basename(download)
            for dist in self.install_eggs(download, self.zip_ok, tmpdir):
                self.package_index.add(dist)
                self.install_egg_scripts(dist)
                print self.installation_report(dist)

        finally:
            if self.build_directory is None:
                shutil.rmtree(tmpdir)




    def install_egg_scripts(self, dist):
        metadata = dist.metadata
        if self.exclude_scripts or not metadata.metadata_isdir('scripts'):
            return

        from distutils.command.build_scripts import first_line_re

        for script_name in metadata.metadata_listdir('scripts'):
            target = os.path.join(self.script_dir, script_name)

            print "Installing", script_name, "script to", self.script_dir

            script_text = metadata.get_metadata('scripts/'+script_name)
            script_text = script_text.replace('\r','\n')
            first, rest = script_text.split('\n',1)

            match = first_line_re.match(first)
            options = ''
            if match:
                options = match.group(1) or ''
                if options:
                    options = ' '+options

            spec = '%s==%s' % (dist.name,dist.version)

            script_text = '\n'.join([
                "#!%s%s" % (os.path.normpath(sys.executable),options),
                "# EASY-INSTALL-SCRIPT: %r,%r" % (spec, script_name),
                "import pkg_resources",
                "pkg_resources.run_main(%r, %r)" % (spec, script_name)
            ])

            f = open(target,"w")
            f.write(script_text)
            f.close()
            





    def install_eggs(self, dist_filename, zip_ok, tmpdir):
        # .egg dirs or files are already built, so just return them
        if dist_filename.lower().endswith('.egg'):
            return [self.install_egg(dist_filename, True, tmpdir)]

        # Anything else, try to extract and build
        if os.path.isfile(dist_filename):
            unpack_archive(dist_filename, tmpdir)  # XXX add progress log

        # Find the setup.py file
        from glob import glob
        setup_script = os.path.join(tmpdir, 'setup.py')
        if not os.path.exists(setup_script):
            setups = glob(os.path.join(tmpdir, '*', 'setup.py'))
            if not setups:
                raise RuntimeError(
                    "Couldn't find a setup script in %s" % dist_filename
                )
            if len(setups)>1:
                raise RuntimeError(
                    "Multiple setup scripts in %s" % dist_filename
                )
            setup_script = setups[0]
        from setuptools.command import bdist_egg
        sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
        try:
            print "Running", setup_script[len(tmpdir)+1:]
            run_setup(setup_script, ['-q', 'bdist_egg'])
        except SystemExit, v:
            raise RuntimeError(
                "Setup script exited with %s" % (v.args[0],)
            )

        eggs = []
        for egg in glob(
            os.path.join(os.path.dirname(setup_script),'dist','*.egg')
        ):
            eggs.append(self.install_egg(egg, zip_ok, tmpdir))

        return eggs

    def install_egg(self, egg_path, zip_ok, tmpdir):

        destination = os.path.join(self.install_dir,os.path.basename(egg_path))
        destination = os.path.abspath(destination)
        ensure_directory(destination)

        if not samefile(egg_path, destination):
            if os.path.isdir(destination):
                shutil.rmtree(destination)
            elif os.path.isfile(destination):
                os.unlink(destination)

            if zip_ok:
                if egg_path.startswith(tmpdir):
                    shutil.move(egg_path, destination)
                else:
                    shutil.copy2(egg_path, destination)

            elif os.path.isdir(egg_path):
                shutil.move(egg_path, destination)

            else:
                os.mkdir(destination)
                unpack_archive(egg_path, destination)   # XXX add progress??

        if os.path.isdir(destination):
            dist = Distribution.from_filename(
                destination, metadata=PathMetadata(
                    destination, os.path.join(destination,'EGG-INFO')
                )
            )
        else:
            metadata = EggMetadata(zipimport.zipimporter(destination))
            dist = Distribution.from_filename(destination,metadata=metadata)

        self.update_pth(dist)
        return dist




    def installation_report(self, dist):
        """Helpful installation message for display to package users"""

        msg = "Installed %(eggloc)s to %(instdir)s"
        if self.multi_version:
            msg += """

Because this distribution was installed --multi-version or --install-dir,
before you can import modules from this package in an application, you
will need to 'import pkg_resources' and then use a 'require()' call
similar to one of these examples, in order to select the desired version:

    pkg_resources.require("%(name)s")  # latest installed version
    pkg_resources.require("%(name)s==%(version)s")  # this exact version
    pkg_resources.require("%(name)s>=%(version)s")  # this version or higher
"""
        if not samefile(get_python_lib(),self.install_dir):
            msg += """

Note also that the installation directory must be on sys.path at runtime for
this to work.  (e.g. by being the application's script directory, by being on
PYTHONPATH, or by being added to sys.path by your code.)
"""
        eggloc = os.path.basename(dist.path)
        instdir = os.path.realpath(self.install_dir)
        name = dist.name
        version = dist.version
        return msg % locals()

    def update_pth(self,dist):
        if self.pth_file is not None:
            remove = self.pth_file.remove
            for d in self.pth_file.get(dist.key,()):    # drop old entries
                remove(d)
            if not self.multi_version:
                self.pth_file.add(dist) # add new entry
            self.pth_file.save()




class PthDistributions(AvailableDistributions):
    """A .pth file with Distribution paths in it"""

    dirty = False

    def __init__(self, filename):
        self.filename = filename; self._load()
        AvailableDistributions.__init__(
            self, list(yield_lines(self.paths)), None, None
        )

    def _load(self):
        self.paths = []
        if os.path.isfile(self.filename):
            self.paths = [line.rstrip() for line in open(self.filename,'rt')]
            while self.paths and not self.paths[-1].strip(): self.paths.pop()

    def save(self):
        """Write changed .pth file back to disk"""
        if self.dirty:
            data = '\n'.join(self.paths+[''])
            f = open(self.filename,'wt')
            f.write(data)
            f.close()
            self.dirty = False

    def add(self,dist):
        """Add `dist` to the distribution map"""
        if dist.path not in self.paths:
            self.paths.append(dist.path); self.dirty = True
        AvailableDistributions.add(self,dist)

    def remove(self,dist):
        """Remove `dist` from the distribution map"""
        while dist.path in self.paths:
            self.paths.remove(dist.path); self.dirty = True
        AvailableDistributions.remove(self,dist)




def main(argv, cmds={'easy_install':easy_install}):
    from setuptools import setup
    try:
        setup(cmdclass = cmds, script_args = ['-q','easy_install', '-v']+argv)
    except RuntimeError, v:
        print >>sys.stderr,"error:",v
        sys.exit(1)


if __name__ == '__main__':
    main(sys.argv[1:])