~logan/ubuntu/raring/distribute/0.6.34

« back to all changes in this revision

Viewing changes to setuptools/command/easy_install.py

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2012-08-29 11:43:26 UTC
  • mfrom: (1.2.1) (14.1.1 sid)
  • mto: This revision was merged to the branch mainline in revision 16.
  • Revision ID: package-import@ubuntu.com-20120829114326-9ahdrcjw4tdscpc1
Tags: 0.6.28-1
New upstream version.

Show diffs side-by-side

added added

removed removed

Lines of Context:
10
10
__ http://packages.python.org/distribute/easy_install.html
11
11
 
12
12
"""
13
 
import sys, os.path, zipimport, shutil, tempfile, zipfile, re, stat, random
 
13
import sys
 
14
import os
 
15
import zipimport
 
16
import shutil
 
17
import tempfile
 
18
import zipfile
 
19
import re
 
20
import stat
 
21
import random
14
22
from glob import glob
15
23
from setuptools import Command, _dont_write_bytecode
16
24
from setuptools.sandbox import run_setup
17
25
from distutils import log, dir_util
 
26
from distutils.util import get_platform
18
27
from distutils.util import convert_path, subst_vars
19
28
from distutils.sysconfig import get_python_lib, get_config_vars
20
29
from distutils.errors import DistutilsArgError, DistutilsOptionError, \
21
30
    DistutilsError, DistutilsPlatformError
22
31
from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
 
32
from setuptools.command import setopt
23
33
from setuptools.archive_util import unpack_archive
24
34
from setuptools.package_index import PackageIndex
25
35
from setuptools.package_index import URL_SCHEME
41
51
import site
42
52
HAS_USER_SITE = not sys.version < "2.6" and site.ENABLE_USER_SITE
43
53
 
 
54
import struct
 
55
def is_64bit():
 
56
    return struct.calcsize("P") == 8
 
57
 
44
58
def samefile(p1,p2):
45
59
    if hasattr(os.path,'samefile') and (
46
60
        os.path.exists(p1) and os.path.exists(p2)
208
222
                            'prefix': prefix,
209
223
                            'sys_exec_prefix': exec_prefix,
210
224
                            'exec_prefix': exec_prefix,
 
225
                            # Only python 3.2+ has abiflags
 
226
                            'abiflags': getattr(sys, 'abiflags', ''),
211
227
                           }
212
228
 
213
229
        if HAS_USER_SITE:
396
412
 
397
413
    def check_site_dir(self):
398
414
        """Verify that self.install_dir is .pth-capable dir, if needed"""
399
 
        print 'install_dir', self.install_dir
 
415
 
400
416
        instdir = normalize_path(self.install_dir)
401
417
        pth_file = os.path.join(instdir,'easy-install.pth')
402
418
 
743
759
        spec = str(dist.as_requirement())
744
760
        is_script = is_python_script(script_text, script_name)
745
761
 
746
 
        if is_script and dev_path:
747
 
            script_text = get_script_header(script_text) + (
748
 
                "# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r\n"
749
 
                "__requires__ = %(spec)r\n"
750
 
                "from pkg_resources import require; require(%(spec)r)\n"
751
 
                "del require\n"
752
 
                "__file__ = %(dev_path)r\n"
753
 
                "execfile(__file__)\n"
754
 
            ) % locals()
755
 
        elif is_script:
756
 
            script_text = get_script_header(script_text) + (
757
 
                "# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r\n"
758
 
                "__requires__ = %(spec)r\n"
759
 
                "import pkg_resources\n"
760
 
                "pkg_resources.run_script(%(spec)r, %(script_name)r)\n"
761
 
            ) % locals()
 
762
        def get_template(filename):
 
763
            """
 
764
            There are a couple of template scripts in the package. This
 
765
            function loads one of them and prepares it for use.
 
766
 
 
767
            These templates use triple-quotes to escape variable
 
768
            substitutions so the scripts get the 2to3 treatment when build
 
769
            on Python 3. The templates cannot use triple-quotes naturally.
 
770
            """
 
771
            raw_bytes = resource_string('setuptools', template_name)
 
772
            template_str = raw_bytes.decode('utf-8')
 
773
            clean_template = template_str.replace('"""', '')
 
774
            return clean_template
 
775
 
 
776
        if is_script:
 
777
            template_name = 'script template.py'
 
778
            if dev_path:
 
779
                template_name = template_name.replace('.py', ' (dev).py')
 
780
            script_text = (get_script_header(script_text) +
 
781
                get_template(template_name) % locals())
762
782
        self.write_script(script_name, _to_ascii(script_text), 'b')
763
783
 
764
784
    def write_script(self, script_name, contents, mode="t", blockers=()):
769
789
        target = os.path.join(self.script_dir, script_name)
770
790
        self.add_output(target)
771
791
 
 
792
        mask = current_umask()
772
793
        if not self.dry_run:
773
794
            ensure_directory(target)
774
795
            f = open(target,"w"+mode)
775
796
            f.write(contents)
776
797
            f.close()
777
 
            chmod(target,0755)
 
798
            chmod(target, 0777-mask)
778
799
 
779
800
 
780
801
 
871
892
        # Create a dummy distribution object until we build the real distro
872
893
        dist = Distribution(None,
873
894
            project_name=cfg.get('metadata','name'),
874
 
            version=cfg.get('metadata','version'), platform="win32"
 
895
            version=cfg.get('metadata','version'), platform=get_platform()
875
896
        )
876
897
 
877
898
        # Convert the .exe to an unpacked egg
1090
1111
 
1091
1112
    def build_and_install(self, setup_script, setup_base):
1092
1113
        args = ['bdist_egg', '--dist-dir']
 
1114
 
1093
1115
        dist_dir = tempfile.mkdtemp(
1094
1116
            prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
1095
1117
        )
1096
1118
        try:
 
1119
            self._set_fetcher_options(os.path.dirname(setup_script))
1097
1120
            args.append(dist_dir)
 
1121
 
1098
1122
            self.run_setup(setup_script, setup_base, args)
1099
1123
            all_eggs = Environment([dist_dir])
1100
1124
            eggs = []
1109
1133
            rmtree(dist_dir)
1110
1134
            log.set_verbosity(self.verbose) # restore our log verbosity
1111
1135
 
 
1136
    def _set_fetcher_options(self, base):
 
1137
        """
 
1138
        When easy_install is about to run bdist_egg on a source dist, that
 
1139
        source dist might have 'setup_requires' directives, requiring
 
1140
        additional fetching. Ensure the fetcher options given to easy_install
 
1141
        are available to that command as well.
 
1142
        """
 
1143
        # find the fetch options from easy_install and write them out
 
1144
        #  to the setup.cfg file.
 
1145
        ei_opts = self.distribution.get_option_dict('easy_install').copy()
 
1146
        fetch_directives = (
 
1147
            'find_links', 'site_dirs', 'index_url', 'optimize',
 
1148
            'site_dirs', 'allow_hosts',
 
1149
        )
 
1150
        fetch_options = {}
 
1151
        for key, val in ei_opts.iteritems():
 
1152
            if key not in fetch_directives: continue
 
1153
            fetch_options[key.replace('_', '-')] = val[1]
 
1154
        # create a settings dictionary suitable for `edit_config`
 
1155
        settings = dict(easy_install=fetch_options)
 
1156
        cfg_filename = os.path.join(base, 'setup.cfg')
 
1157
        setopt.edit_config(cfg_filename, settings)
 
1158
 
 
1159
 
1112
1160
    def update_pth(self,dist):
1113
1161
        if self.pth_file is None:
1114
1162
            return
1470
1518
        f.seek(prepended-(12+cfglen))
1471
1519
        cfg = ConfigParser.RawConfigParser({'version':'','target_version':''})
1472
1520
        try:
1473
 
            cfg.readfp(StringIO.StringIO(f.read(cfglen).split(chr(0),1)[0]))
 
1521
            part = f.read(cfglen)
 
1522
            # part is in bytes, but we need to read up to the first null
 
1523
            #  byte.
 
1524
            if sys.version_info >= (2,6):
 
1525
                null_byte = bytes([0])
 
1526
            else:
 
1527
                null_byte = chr(0)
 
1528
            config = part.split(null_byte, 1)[0]
 
1529
            # Now the config is in bytes, but on Python 3, it must be
 
1530
            #  unicode for the RawConfigParser, so decode it. Is this the
 
1531
            #  right encoding?
 
1532
            config = config.decode('ascii')
 
1533
            cfg.readfp(StringIO.StringIO(config))
1474
1534
        except ConfigParser.Error:
1475
1535
            return None
1476
1536
        if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
1493
1553
    prefixes = [
1494
1554
        ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
1495
1555
        ('PLATLIB/', ''),
1496
 
        ('SCRIPTS/', 'EGG-INFO/scripts/')
 
1556
        ('SCRIPTS/', 'EGG-INFO/scripts/'),
 
1557
        ('DATA/LIB/site-packages', ''),
1497
1558
    ]
1498
1559
    z = zipfile.ZipFile(exe_filename)
1499
1560
    try:
1634
1695
def get_script_header(script_text, executable=sys_executable, wininst=False):
1635
1696
    """Create a #! line, getting options (if any) from script_text"""
1636
1697
    from distutils.command.build_scripts import first_line_re
 
1698
 
 
1699
    # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
 
1700
    if not isinstance(first_line_re.pattern, str):
 
1701
        first_line_re = re.compile(first_line_re.pattern.decode())
 
1702
 
1637
1703
    first = (script_text+'\n').splitlines()[0]
1638
1704
    match = first_line_re.match(first)
1639
1705
    options = ''
1808
1874
                    ext, launcher = '-script.py', 'cli.exe'
1809
1875
                    old = ['.py','.pyc','.pyo']
1810
1876
                    new_header = re.sub('(?i)pythonw.exe','python.exe',header)
1811
 
 
 
1877
                if is_64bit():
 
1878
                    launcher = launcher.replace(".", "-64.")
 
1879
                else:
 
1880
                    launcher = launcher.replace(".", "-32.")
1812
1881
                if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
1813
1882
                    hdr = new_header
1814
1883
                else:
1858
1927
    except os.error:
1859
1928
        onerror(os.rmdir, path, sys.exc_info())
1860
1929
 
 
1930
def current_umask():
 
1931
    tmp = os.umask(022)
 
1932
    os.umask(tmp)
 
1933
    return tmp
 
1934
 
1861
1935
def bootstrap():
1862
1936
    # This function is called when setuptools*.egg is run using /bin/sh
1863
1937
    import setuptools; argv0 = os.path.dirname(setuptools.__path__[0])