home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2410 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  54.7 KB  |  1,524 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import sys
  5. import os.path as os
  6. import zipimport
  7. import shutil
  8. import tempfile
  9. import zipfile
  10. import re
  11. import stat
  12. import random
  13. from glob import glob
  14. from setuptools import Command
  15. from setuptools.sandbox import run_setup
  16. from distutils import log, dir_util
  17. from distutils.sysconfig import get_python_lib
  18. from distutils.errors import DistutilsArgError, DistutilsOptionError, DistutilsError
  19. from setuptools.archive_util import unpack_archive
  20. from setuptools.package_index import PackageIndex, parse_bdist_wininst
  21. from setuptools.package_index import URL_SCHEME
  22. from setuptools.command import bdist_egg, egg_info
  23. from pkg_resources import *
  24. sys_executable = os.path.normpath(sys.executable)
  25. __all__ = [
  26.     'samefile',
  27.     'easy_install',
  28.     'PthDistributions',
  29.     'extract_wininst_cfg',
  30.     'main',
  31.     'get_exe_prefixes']
  32.  
  33. def samefile(p1, p2):
  34.     if hasattr(os.path, 'samefile') and os.path.exists(p1) and os.path.exists(p2):
  35.         return os.path.samefile(p1, p2)
  36.     return os.path.normpath(os.path.normcase(p1)) == os.path.normpath(os.path.normcase(p2))
  37.  
  38.  
  39. class easy_install(Command):
  40.     description = 'Find/get/install Python packages'
  41.     command_consumes_arguments = True
  42.     user_options = [
  43.         ('prefix=', None, 'installation prefix'),
  44.         ('zip-ok', 'z', 'install package as a zipfile'),
  45.         ('multi-version', 'm', 'make apps have to require() a version'),
  46.         ('upgrade', 'U', 'force upgrade (searches PyPI for latest versions)'),
  47.         ('install-dir=', 'd', 'install package to DIR'),
  48.         ('script-dir=', 's', 'install scripts to DIR'),
  49.         ('exclude-scripts', 'x', "Don't install scripts"),
  50.         ('always-copy', 'a', 'Copy all needed packages to install dir'),
  51.         ('index-url=', 'i', 'base URL of Python Package Index'),
  52.         ('find-links=', 'f', 'additional URL(s) to search for packages'),
  53.         ('delete-conflicting', 'D', "no longer needed; don't use this"),
  54.         ('ignore-conflicts-at-my-risk', None, "no longer needed; don't use this"),
  55.         ('build-directory=', 'b', 'download/extract/build in DIR; keep the results'),
  56.         ('optimize=', 'O', 'also compile with optimization: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0]'),
  57.         ('record=', None, 'filename in which to record list of installed files'),
  58.         ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
  59.         ('site-dirs=', 'S', 'list of directories where .pth files work'),
  60.         ('editable', 'e', 'Install specified packages in editable form'),
  61.         ('no-deps', 'N', "don't install dependencies"),
  62.         ('allow-hosts=', 'H', 'pattern(s) that hostnames must match'),
  63.         ('local-snapshots-ok', 'l', 'allow building eggs from local checkouts')]
  64.     boolean_options = [
  65.         'zip-ok',
  66.         'multi-version',
  67.         'exclude-scripts',
  68.         'upgrade',
  69.         'always-copy',
  70.         'delete-conflicting',
  71.         'ignore-conflicts-at-my-risk',
  72.         'editable',
  73.         'no-deps',
  74.         'local-snapshots-ok']
  75.     negative_opt = {
  76.         'always-unzip': 'zip-ok' }
  77.     create_index = PackageIndex
  78.     
  79.     def initialize_options(self):
  80.         self.zip_ok = None
  81.         self.local_snapshots_ok = None
  82.         self.install_dir = None
  83.         self.script_dir = None
  84.         self.exclude_scripts = None
  85.         self.index_url = None
  86.         self.find_links = None
  87.         self.build_directory = None
  88.         self.args = None
  89.         self.optimize = None
  90.         self.record = None
  91.         self.upgrade = None
  92.         self.always_copy = None
  93.         self.multi_version = None
  94.         self.editable = None
  95.         self.no_deps = None
  96.         self.allow_hosts = None
  97.         self.root = None
  98.         self.prefix = None
  99.         self.no_report = None
  100.         self.package_index = None
  101.         self.pth_file = None
  102.         self.always_copy_from = None
  103.         self.delete_conflicting = None
  104.         self.ignore_conflicts_at_my_risk = None
  105.         self.site_dirs = None
  106.         self.installed_projects = { }
  107.         self.sitepy_installed = False
  108.         self._dry_run = None
  109.         self.verbose = self.distribution.verbose
  110.         self.distribution._set_command_options(self, self.distribution.get_option_dict('easy_install'))
  111.  
  112.     
  113.     def delete_blockers(self, blockers):
  114.         for filename in blockers:
  115.             if os.path.exists(filename) or os.path.islink(filename):
  116.                 log.info('Deleting %s', filename)
  117.                 if not self.dry_run:
  118.                     if os.path.isdir(filename) and not os.path.islink(filename):
  119.                         rmtree(filename)
  120.                     else:
  121.                         os.unlink(filename)
  122.                 
  123.             self.dry_run
  124.         
  125.  
  126.     
  127.     def finalize_options(self):
  128.         self._expand('install_dir', 'script_dir', 'build_directory', 'site_dirs')
  129.         if self.script_dir is None:
  130.             self.script_dir = self.install_dir
  131.         
  132.         self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))
  133.         self.set_undefined_options('install_scripts', ('install_dir', 'script_dir'))
  134.         self.set_undefined_options('install', ('record', 'record'))
  135.         normpath = map(normalize_path, sys.path)
  136.         self.all_site_dirs = get_site_dirs()
  137.         if self.site_dirs is not None:
  138.             site_dirs = [ os.path.expanduser(s.strip()) for s in self.site_dirs.split(',') ]
  139.             for d in site_dirs:
  140.                 if not os.path.isdir(d):
  141.                     log.warn('%s (in --site-dirs) does not exist', d)
  142.                     continue
  143.                 []
  144.                 if normalize_path(d) not in normpath:
  145.                     raise DistutilsOptionError(d + ' (in --site-dirs) is not on sys.path')
  146.                 normalize_path(d) not in normpath
  147.                 self.all_site_dirs.append(normalize_path(d))
  148.             
  149.         
  150.         if not self.editable:
  151.             self.check_site_dir()
  152.         
  153.         if not self.index_url:
  154.             pass
  155.         self.index_url = 'http://pypi.python.org/simple'
  156.         self.shadow_path = self.all_site_dirs[:]
  157.         for path_item in (self.install_dir, normalize_path(self.script_dir)):
  158.             if path_item not in self.shadow_path:
  159.                 self.shadow_path.insert(0, path_item)
  160.                 continue
  161.         
  162.         if self.package_index is None:
  163.             self.package_index = self.create_index(self.index_url, search_path = self.shadow_path, hosts = hosts)
  164.         
  165.         self.local_index = Environment(self.shadow_path + sys.path)
  166.         if self.find_links is not None:
  167.             if isinstance(self.find_links, basestring):
  168.                 self.find_links = self.find_links.split()
  169.             
  170.         else:
  171.             self.find_links = []
  172.         if self.local_snapshots_ok:
  173.             self.package_index.scan_egg_links(self.shadow_path + sys.path)
  174.         
  175.         self.package_index.add_find_links(self.find_links)
  176.         self.set_undefined_options('install_lib', ('optimize', 'optimize'))
  177.         if not isinstance(self.optimize, int):
  178.             
  179.             try:
  180.                 self.optimize = int(self.optimize)
  181.                 if self.optimize <= self.optimize:
  182.                     pass
  183.                 elif not self.optimize <= 2:
  184.                     raise ValueError
  185.             except ValueError:
  186.                 raise DistutilsOptionError('--optimize must be 0, 1, or 2')
  187.             except:
  188.                 None<EXCEPTION MATCH>ValueError
  189.             
  190.  
  191.         None<EXCEPTION MATCH>ValueError
  192.         if self.delete_conflicting and self.ignore_conflicts_at_my_risk:
  193.             raise DistutilsOptionError("Can't use both --delete-conflicting and --ignore-conflicts-at-my-risk at the same time")
  194.         self.ignore_conflicts_at_my_risk
  195.         if self.editable and not (self.build_directory):
  196.             raise DistutilsArgError('Must specify a build directory (-b) when using --editable')
  197.         not (self.build_directory)
  198.         if not self.args:
  199.             raise DistutilsArgError('No urls, filenames, or requirements specified (see --help)')
  200.         self.args
  201.         self.outputs = []
  202.  
  203.     
  204.     def run(self):
  205.         if self.verbose != self.distribution.verbose:
  206.             log.set_verbosity(self.verbose)
  207.         
  208.         
  209.         try:
  210.             for spec in self.args:
  211.                 self.easy_install(spec, not (self.no_deps))
  212.             
  213.             if self.record:
  214.                 outputs = self.outputs
  215.                 if self.root:
  216.                     root_len = len(self.root)
  217.                     for counter in xrange(len(outputs)):
  218.                         outputs[counter] = outputs[counter][root_len:]
  219.                     
  220.                 
  221.                 file_util = file_util
  222.                 import distutils
  223.                 self.execute(file_util.write_file, (self.record, outputs), "writing list of installed files to '%s'" % self.record)
  224.             
  225.             self.warn_deprecated_options()
  226.         finally:
  227.             log.set_verbosity(self.distribution.verbose)
  228.  
  229.  
  230.     
  231.     def pseudo_tempname(self):
  232.         
  233.         try:
  234.             pid = os.getpid()
  235.         except:
  236.             pid = random.randint(0, sys.maxint)
  237.  
  238.         return os.path.join(self.install_dir, 'test-easy-install-%s' % pid)
  239.  
  240.     
  241.     def warn_deprecated_options(self):
  242.         if self.delete_conflicting or self.ignore_conflicts_at_my_risk:
  243.             log.warn('Note: The -D, --delete-conflicting and --ignore-conflicts-at-my-risk no longer have any purpose and should not be used.')
  244.         
  245.  
  246.     
  247.     def check_site_dir(self):
  248.         instdir = normalize_path(self.install_dir)
  249.         pth_file = os.path.join(instdir, 'easy-install.pth')
  250.         is_site_dir = instdir in self.all_site_dirs
  251.         if not is_site_dir:
  252.             is_site_dir = self.check_pth_processing()
  253.         else:
  254.             testfile = self.pseudo_tempname() + '.write-test'
  255.             test_exists = os.path.exists(testfile)
  256.             
  257.             try:
  258.                 if test_exists:
  259.                     os.unlink(testfile)
  260.                 
  261.                 open(testfile, 'w').close()
  262.                 os.unlink(testfile)
  263.             except (OSError, IOError):
  264.                 self.cant_write_to_target()
  265.  
  266.         if not is_site_dir and not (self.multi_version):
  267.             raise DistutilsError(self.no_default_version_msg())
  268.         not (self.multi_version)
  269.         if is_site_dir:
  270.             if self.pth_file is None:
  271.                 self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
  272.             
  273.         else:
  274.             self.pth_file = None
  275.         PYTHONPATH = os.environ.get('PYTHONPATH', '').split(os.pathsep)
  276.         if instdir not in map(normalize_path, filter(None, PYTHONPATH)):
  277.             self.sitepy_installed = True
  278.         elif self.multi_version and not os.path.exists(pth_file):
  279.             self.sitepy_installed = True
  280.             self.pth_file = None
  281.         
  282.         self.install_dir = instdir
  283.  
  284.     
  285.     def cant_write_to_target(self):
  286.         msg = "can't create or remove files in install directory\n\nThe following error occurred while trying to add or remove files in the\ninstallation directory:\n\n    %s\n\nThe installation directory you specified (via --install-dir, --prefix, or\nthe distutils default setting) was:\n\n    %s\n" % (sys.exc_info()[1], self.install_dir)
  287.         if not os.path.exists(self.install_dir):
  288.             msg += '\nThis directory does not currently exist.  Please create it and try again, or\nchoose a different installation directory (using the -d or --install-dir\noption).\n'
  289.         else:
  290.             msg += '\nPerhaps your account does not have write access to this directory?  If the\ninstallation directory is a system-owned directory, you may need to sign in\nas the administrator or "root" account.  If you do not have administrative\naccess to this machine, you may wish to choose a different installation\ndirectory, preferably one that is listed in your PYTHONPATH environment\nvariable.\n\nFor information on other options, you may wish to consult the\ndocumentation at:\n\n  http://peak.telecommunity.com/EasyInstall.html\n\nPlease make the appropriate changes for your system and try again.\n'
  291.         raise DistutilsError(msg)
  292.  
  293.     
  294.     def check_pth_processing(self):
  295.         instdir = self.install_dir
  296.         log.info('Checking .pth file support in %s', instdir)
  297.         pth_file = self.pseudo_tempname() + '.pth'
  298.         ok_file = pth_file + '.ok'
  299.         ok_exists = os.path.exists(ok_file)
  300.         
  301.         try:
  302.             if ok_exists:
  303.                 os.unlink(ok_file)
  304.             
  305.             f = open(pth_file, 'w')
  306.         except (OSError, IOError):
  307.             self.cant_write_to_target()
  308.  
  309.         
  310.         try:
  311.             f.write("import os;open(%r,'w').write('OK')\n" % (ok_file,))
  312.             f.close()
  313.             f = None
  314.             executable = sys.executable
  315.             if os.name == 'nt':
  316.                 (dirname, basename) = os.path.split(executable)
  317.                 alt = os.path.join(dirname, 'pythonw.exe')
  318.                 if basename.lower() == 'python.exe' and os.path.exists(alt):
  319.                     executable = alt
  320.                 
  321.             
  322.             spawn = spawn
  323.             import distutils.spawn
  324.             spawn([
  325.                 executable,
  326.                 '-E',
  327.                 '-c',
  328.                 'pass'], 0)
  329.             if os.path.exists(ok_file):
  330.                 log.info('TEST PASSED: %s appears to support .pth files', instdir)
  331.                 return True
  332.         finally:
  333.             if f:
  334.                 f.close()
  335.             
  336.             if os.path.exists(ok_file):
  337.                 os.unlink(ok_file)
  338.             
  339.             if os.path.exists(pth_file):
  340.                 os.unlink(pth_file)
  341.             
  342.  
  343.         if not self.multi_version:
  344.             log.warn('TEST FAILED: %s does NOT support .pth files', instdir)
  345.         
  346.         return False
  347.  
  348.     
  349.     def install_egg_scripts(self, dist):
  350.         if not (self.exclude_scripts) and dist.metadata_isdir('scripts'):
  351.             for script_name in dist.metadata_listdir('scripts'):
  352.                 self.install_script(dist, script_name, dist.get_metadata('scripts/' + script_name))
  353.             
  354.         
  355.         self.install_wrapper_scripts(dist)
  356.  
  357.     
  358.     def add_output(self, path):
  359.         if os.path.isdir(path):
  360.             for base, dirs, files in os.walk(path):
  361.                 for filename in files:
  362.                     self.outputs.append(os.path.join(base, filename))
  363.                 
  364.             
  365.         else:
  366.             self.outputs.append(path)
  367.  
  368.     
  369.     def not_editable(self, spec):
  370.         if self.editable:
  371.             raise DistutilsArgError("Invalid argument %r: you can't use filenames or URLs with --editable (except via the --find-links option)." % (spec,))
  372.         self.editable
  373.  
  374.     
  375.     def check_editable(self, spec):
  376.         if not self.editable:
  377.             return None
  378.         if os.path.exists(os.path.join(self.build_directory, spec.key)):
  379.             raise DistutilsArgError("%r already exists in %s; can't do a checkout there" % (spec.key, self.build_directory))
  380.         os.path.exists(os.path.join(self.build_directory, spec.key))
  381.  
  382.     
  383.     def easy_install(self, spec, deps = False):
  384.         tmpdir = tempfile.mkdtemp(prefix = 'easy_install-')
  385.         download = None
  386.         if not self.editable:
  387.             self.install_site_py()
  388.         
  389.         
  390.         try:
  391.             self.check_editable(spec)
  392.             dist = self.package_index.fetch_distribution(spec, tmpdir, self.upgrade, self.editable, not (self.always_copy))
  393.             if dist is None:
  394.                 msg = 'Could not find suitable distribution for %r' % spec
  395.                 if self.always_copy:
  396.                     msg += ' (--always-copy skips system and development eggs)'
  397.                 
  398.                 raise DistutilsError(msg)
  399.             dist is None
  400.             if dist.precedence == DEVELOP_DIST:
  401.                 self.process_distribution(spec, dist, deps, 'Using')
  402.                 return dist
  403.             return self.install_item(spec, dist.location, tmpdir, deps)
  404.         finally:
  405.             if os.path.exists(tmpdir):
  406.                 rmtree(tmpdir)
  407.             
  408.  
  409.  
  410.     
  411.     def install_item(self, spec, download, tmpdir, deps, install_needed = False):
  412.         if not install_needed:
  413.             pass
  414.         install_needed = self.always_copy
  415.         if not install_needed:
  416.             pass
  417.         install_needed = os.path.dirname(download) == tmpdir
  418.         if not install_needed:
  419.             pass
  420.         install_needed = not download.endswith('.egg')
  421.         if install_needed and self.always_copy_from is not None:
  422.             pass
  423.         install_needed = os.path.dirname(normalize_path(download)) == normalize_path(self.always_copy_from)
  424.         if spec and not install_needed:
  425.             for dist in self.local_index[spec.project_name]:
  426.                 if dist.location == download:
  427.                     break
  428.                     continue
  429.             else:
  430.                 install_needed = True
  431.         
  432.         log.info('Processing %s', os.path.basename(download))
  433.         if install_needed:
  434.             dists = self.install_eggs(spec, download, tmpdir)
  435.             for dist in dists:
  436.                 self.process_distribution(spec, dist, deps)
  437.             
  438.         else:
  439.             dists = [
  440.                 self.check_conflicts(self.egg_distribution(download))]
  441.             self.process_distribution(spec, dists[0], deps, 'Using')
  442.         if spec is not None:
  443.             for dist in dists:
  444.                 if dist in spec:
  445.                     return dist
  446.             
  447.         
  448.  
  449.     
  450.     def process_distribution(self, requirement, dist, deps = True, *info):
  451.         self.update_pth(dist)
  452.         self.package_index.add(dist)
  453.         self.local_index.add(dist)
  454.         self.install_egg_scripts(dist)
  455.         self.installed_projects[dist.key] = dist
  456.         log.info(self.installation_report(requirement, dist, *info))
  457.         if dist.has_metadata('dependency_links.txt'):
  458.             self.package_index.add_find_links(dist.get_metadata_lines('dependency_links.txt'))
  459.         
  460.         if not deps and not (self.always_copy):
  461.             return None
  462.         if requirement is not None and dist.key != requirement.key:
  463.             log.warn('Skipping dependencies for %s', dist)
  464.             return None
  465.         log.info('Processing dependencies for %s', requirement)
  466.         
  467.         try:
  468.             distros = WorkingSet([]).resolve([
  469.                 requirement], self.local_index, self.easy_install)
  470.         except DistributionNotFound:
  471.             None if requirement is None or dist not in requirement else not (self.always_copy)
  472.             e = None if requirement is None or dist not in requirement else not (self.always_copy)
  473.             raise DistutilsError('Could not find required distribution %s' % e.args)
  474.         except VersionConflict:
  475.             e = None
  476.             raise DistutilsError('Installed distribution %s conflicts with requirement %s' % e.args)
  477.         except:
  478.             None if requirement is None or dist not in requirement else not (self.always_copy)
  479.  
  480.         if self.always_copy or self.always_copy_from:
  481.             for dist in distros:
  482.                 if dist.key not in self.installed_projects:
  483.                     self.easy_install(dist.as_requirement())
  484.                     continue
  485.                 None if requirement is None or dist not in requirement else not (self.always_copy)
  486.             
  487.         
  488.         log.info('Finished processing dependencies for %s', requirement)
  489.  
  490.     
  491.     def should_unzip(self, dist):
  492.         if self.zip_ok is not None:
  493.             return not (self.zip_ok)
  494.         if dist.has_metadata('not-zip-safe'):
  495.             return True
  496.         if not dist.has_metadata('zip-safe'):
  497.             return True
  498.         return False
  499.  
  500.     
  501.     def maybe_move(self, spec, dist_filename, setup_base):
  502.         dst = os.path.join(self.build_directory, spec.key)
  503.         if os.path.exists(dst):
  504.             log.warn('%r already exists in %s; build directory %s will not be kept', spec.key, self.build_directory, setup_base)
  505.             return setup_base
  506.         if os.path.isdir(dist_filename):
  507.             setup_base = dist_filename
  508.         elif os.path.dirname(dist_filename) == setup_base:
  509.             os.unlink(dist_filename)
  510.         
  511.         contents = os.listdir(setup_base)
  512.         if len(contents) == 1:
  513.             dist_filename = os.path.join(setup_base, contents[0])
  514.             if os.path.isdir(dist_filename):
  515.                 setup_base = dist_filename
  516.             
  517.         
  518.         ensure_directory(dst)
  519.         shutil.move(setup_base, dst)
  520.         return dst
  521.  
  522.     
  523.     def install_wrapper_scripts(self, dist):
  524.         if not self.exclude_scripts:
  525.             for args in get_script_args(dist):
  526.                 self.write_script(*args)
  527.             
  528.         
  529.  
  530.     
  531.     def install_script(self, dist, script_name, script_text, dev_path = None):
  532.         spec = str(dist.as_requirement())
  533.         is_script = is_python_script(script_text, script_name)
  534.         if is_script and dev_path:
  535.             script_text = get_script_header(script_text) + '# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r\n__requires__ = %(spec)r\nfrom pkg_resources import require; require(%(spec)r)\ndel require\n__file__ = %(dev_path)r\nexecfile(__file__)\n' % locals()
  536.         elif is_script:
  537.             script_text = get_script_header(script_text) + '# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r\n__requires__ = %(spec)r\nimport pkg_resources\npkg_resources.run_script(%(spec)r, %(script_name)r)\n' % locals()
  538.         
  539.         self.write_script(script_name, script_text, 'b')
  540.  
  541.     
  542.     def write_script(self, script_name, contents, mode = 't', blockers = ()):
  543.         []([ os.path.join(self.script_dir, x) for x in blockers ])
  544.         log.info('Installing %s script to %s', script_name, self.script_dir)
  545.         target = os.path.join(self.script_dir, script_name)
  546.         self.add_output(target)
  547.  
  548.     
  549.     def install_eggs(self, spec, dist_filename, tmpdir):
  550.         if dist_filename.lower().endswith('.egg'):
  551.             return [
  552.                 self.install_egg(dist_filename, tmpdir)]
  553.         if dist_filename.lower().endswith('.exe'):
  554.             return [
  555.                 self.install_exe(dist_filename, tmpdir)]
  556.         setup_base = tmpdir
  557.         if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
  558.             unpack_archive(dist_filename, tmpdir, self.unpack_progress)
  559.         elif os.path.isdir(dist_filename):
  560.             setup_base = os.path.abspath(dist_filename)
  561.         
  562.         if setup_base.startswith(tmpdir) and self.build_directory and spec is not None:
  563.             setup_base = self.maybe_move(spec, dist_filename, setup_base)
  564.         
  565.         setup_script = os.path.join(setup_base, 'setup.py')
  566.         if not os.path.exists(setup_script):
  567.             setups = glob(os.path.join(setup_base, '*', 'setup.py'))
  568.             if not setups:
  569.                 raise DistutilsError("Couldn't find a setup script in %s" % os.path.abspath(dist_filename))
  570.             setups
  571.             if len(setups) > 1:
  572.                 raise DistutilsError('Multiple setup scripts in %s' % os.path.abspath(dist_filename))
  573.             len(setups) > 1
  574.             setup_script = setups[0]
  575.         
  576.         if self.editable:
  577.             log.info(self.report_editable(spec, setup_script))
  578.             return []
  579.         return self.build_and_install(setup_script, setup_base)
  580.  
  581.     
  582.     def egg_distribution(self, egg_path):
  583.         if os.path.isdir(egg_path):
  584.             metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO'))
  585.         else:
  586.             metadata = EggMetadata(zipimport.zipimporter(egg_path))
  587.         return Distribution.from_filename(egg_path, metadata = metadata)
  588.  
  589.     
  590.     def install_egg(self, egg_path, tmpdir):
  591.         destination = os.path.join(self.install_dir, os.path.basename(egg_path))
  592.         destination = os.path.abspath(destination)
  593.         if not self.dry_run:
  594.             ensure_directory(destination)
  595.         
  596.         dist = self.egg_distribution(egg_path)
  597.         self.check_conflicts(dist)
  598.         if not samefile(egg_path, destination):
  599.             if os.path.isdir(destination) and not os.path.islink(destination):
  600.                 dir_util.remove_tree(destination, dry_run = self.dry_run)
  601.             elif os.path.exists(destination):
  602.                 self.execute(os.unlink, (destination,), 'Removing ' + destination)
  603.             
  604.             uncache_zipdir(destination)
  605.             if os.path.isdir(egg_path):
  606.                 if egg_path.startswith(tmpdir):
  607.                     f = shutil.move
  608.                     m = 'Moving'
  609.                 else:
  610.                     f = shutil.copytree
  611.                     m = 'Copying'
  612.             elif self.should_unzip(dist):
  613.                 self.mkpath(destination)
  614.                 f = self.unpack_and_compile
  615.                 m = 'Extracting'
  616.             elif egg_path.startswith(tmpdir):
  617.                 f = shutil.move
  618.                 m = 'Moving'
  619.             else:
  620.                 f = shutil.copy2
  621.                 m = 'Copying'
  622.             self.execute(f, (egg_path, destination), (m + ' %s to %s') % (os.path.basename(egg_path), os.path.dirname(destination)))
  623.         
  624.         self.add_output(destination)
  625.         return self.egg_distribution(destination)
  626.  
  627.     
  628.     def install_exe(self, dist_filename, tmpdir):
  629.         cfg = extract_wininst_cfg(dist_filename)
  630.         if cfg is None:
  631.             raise DistutilsError('%s is not a valid distutils Windows .exe' % dist_filename)
  632.         cfg is None
  633.         dist = Distribution(None, project_name = cfg.get('metadata', 'name'), version = cfg.get('metadata', 'version'), platform = 'win32')
  634.         egg_path = dist.location = os.path.join(tmpdir, dist.egg_name() + '.egg')
  635.         egg_tmp = egg_path + '.tmp'
  636.         egg_info = os.path.join(egg_tmp, 'EGG-INFO')
  637.         pkg_inf = os.path.join(egg_info, 'PKG-INFO')
  638.         ensure_directory(pkg_inf)
  639.         dist._provider = PathMetadata(egg_tmp, egg_info)
  640.         self.exe_to_egg(dist_filename, egg_tmp)
  641.         if not os.path.exists(pkg_inf):
  642.             f = open(pkg_inf, 'w')
  643.             f.write('Metadata-Version: 1.0\n')
  644.             for k, v in cfg.items('metadata'):
  645.                 if k != 'target_version':
  646.                     f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
  647.                     continue
  648.             
  649.             f.close()
  650.         
  651.         script_dir = os.path.join(egg_info, 'scripts')
  652.         []([ os.path.join(script_dir, args[0]) for args in get_script_args(dist) ])
  653.         bdist_egg.make_zipfile(egg_path, egg_tmp, verbose = self.verbose, dry_run = self.dry_run)
  654.         return self.install_egg(egg_path, tmpdir)
  655.  
  656.     
  657.     def exe_to_egg(self, dist_filename, egg_tmp):
  658.         prefixes = get_exe_prefixes(dist_filename)
  659.         to_compile = []
  660.         native_libs = []
  661.         top_level = { }
  662.         
  663.         def process(src, dst):
  664.             s = src.lower()
  665.             for old, new in prefixes:
  666.                 if s.startswith(old):
  667.                     src = new + src[len(old):]
  668.                     parts = src.split('/')
  669.                     dst = os.path.join(egg_tmp, *parts)
  670.                     dl = dst.lower()
  671.                     if dl.endswith('.pyd') or dl.endswith('.dll'):
  672.                         parts[-1] = bdist_egg.strip_module(parts[-1])
  673.                         top_level[os.path.splitext(parts[0])[0]] = 1
  674.                         native_libs.append(src)
  675.                     elif dl.endswith('.py') and old != 'SCRIPTS/':
  676.                         top_level[os.path.splitext(parts[0])[0]] = 1
  677.                         to_compile.append(dst)
  678.                     
  679.                     return dst
  680.             
  681.             if not src.endswith('.pth'):
  682.                 log.warn("WARNING: can't process %s", src)
  683.             
  684.  
  685.         unpack_archive(dist_filename, egg_tmp, process)
  686.         stubs = []
  687.         for res in native_libs:
  688.             if res.lower().endswith('.pyd'):
  689.                 parts = res.split('/')
  690.                 resource = parts[-1]
  691.                 parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
  692.                 pyfile = os.path.join(egg_tmp, *parts)
  693.                 to_compile.append(pyfile)
  694.                 stubs.append(pyfile)
  695.                 bdist_egg.write_stub(resource, pyfile)
  696.                 continue
  697.             (None, None, None, None, None)
  698.         
  699.         self.byte_compile(to_compile)
  700.         bdist_egg.write_safety_flag(os.path.join(egg_tmp, 'EGG-INFO'), bdist_egg.analyze_egg(egg_tmp, stubs))
  701.         for name in ('top_level', 'native_libs'):
  702.             if locals()[name]:
  703.                 txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
  704.                 if not os.path.exists(txt):
  705.                     open(txt, 'w').write('\n'.join(locals()[name]) + '\n')
  706.                 
  707.             os.path.exists(txt)
  708.         
  709.  
  710.     
  711.     def check_conflicts(self, dist):
  712.         return dist
  713.         find_module = find_module
  714.         get_suffixes = get_suffixes
  715.         import imp
  716.         glob = glob
  717.         import glob
  718.         blockers = []
  719.         names = dict.fromkeys(dist._get_metadata('top_level.txt'))
  720.         exts = {
  721.             '.pyc': 1,
  722.             '.pyo': 1 }
  723.         for ext, mode, typ in get_suffixes():
  724.             exts[ext] = 1
  725.         
  726.         for path, files in expand_paths([
  727.             self.install_dir] + self.all_site_dirs):
  728.             for filename in files:
  729.                 (base, ext) = os.path.splitext(filename)
  730.                 if base in names:
  731.                     if not ext:
  732.                         
  733.                         try:
  734.                             (f, filename, descr) = find_module(base, [
  735.                                 path])
  736.                         except ImportError:
  737.                             continue
  738.  
  739.                         if f:
  740.                             f.close()
  741.                         
  742.                         if filename not in blockers:
  743.                             blockers.append(filename)
  744.                         
  745.                     elif ext in exts and base != 'site':
  746.                         blockers.append(os.path.join(path, filename))
  747.                     
  748.                 base != 'site'
  749.             
  750.         
  751.         if blockers:
  752.             self.found_conflicts(dist, blockers)
  753.         
  754.         return dist
  755.  
  756.     
  757.     def found_conflicts(self, dist, blockers):
  758.         if self.delete_conflicting:
  759.             log.warn('Attempting to delete conflicting packages:')
  760.             return self.delete_blockers(blockers)
  761.         msg = "-------------------------------------------------------------------------\nCONFLICT WARNING:\n\nThe following modules or packages have the same names as modules or\npackages being installed, and will be *before* the installed packages in\nPython's search path.  You MUST remove all of the relevant files and\ndirectories before you will be able to use the package(s) you are\ninstalling:\n\n   %s\n\n" % '\n   '.join(blockers)
  762.         if self.ignore_conflicts_at_my_risk:
  763.             msg += "(Note: you can run EasyInstall on '%s' with the\n--delete-conflicting option to attempt deletion of the above files\nand/or directories.)\n" % dist.project_name
  764.         else:
  765.             msg += 'Note: you can attempt this installation again with EasyInstall, and use\neither the --delete-conflicting (-D) option or the\n--ignore-conflicts-at-my-risk option, to either delete the above files\nand directories, or to ignore the conflicts, respectively.  Note that if\nyou ignore the conflicts, the installed package(s) may not work.\n'
  766.         msg += '-------------------------------------------------------------------------\n'
  767.         sys.stderr.write(msg)
  768.         sys.stderr.flush()
  769.         if not self.ignore_conflicts_at_my_risk:
  770.             raise DistutilsError('Installation aborted due to conflicts')
  771.         self.ignore_conflicts_at_my_risk
  772.  
  773.     
  774.     def installation_report(self, req, dist, what = 'Installed'):
  775.         msg = '\n%(what)s %(eggloc)s%(extras)s'
  776.         if self.multi_version and not (self.no_report):
  777.             msg += '\n\nBecause this distribution was installed --multi-version, before you can\nimport modules from this package in an application, you will need to\n\'import pkg_resources\' and then use a \'require()\' call similar to one of\nthese examples, in order to select the desired version:\n\n    pkg_resources.require("%(name)s")  # latest installed version\n    pkg_resources.require("%(name)s==%(version)s")  # this exact version\n    pkg_resources.require("%(name)s>=%(version)s")  # this version or higher\n'
  778.             if self.install_dir not in map(normalize_path, sys.path):
  779.                 msg += "\n\nNote also that the installation directory must be on sys.path at runtime for\nthis to work.  (e.g. by being the application's script directory, by being on\nPYTHONPATH, or by being added to sys.path by your code.)\n"
  780.             
  781.         
  782.         eggloc = dist.location
  783.         name = dist.project_name
  784.         version = dist.version
  785.         extras = ''
  786.         return msg % locals()
  787.  
  788.     
  789.     def report_editable(self, spec, setup_script):
  790.         dirname = os.path.dirname(setup_script)
  791.         python = sys.executable
  792.         return '\nExtracted editable version of %(spec)s to %(dirname)s\n\nIf it uses setuptools in its setup script, you can activate it in\n"development" mode by going to that directory and running::\n\n    %(python)s setup.py develop\n\nSee the setuptools documentation for the "develop" command for more info.\n' % locals()
  793.  
  794.     
  795.     def run_setup(self, setup_script, setup_base, args):
  796.         sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
  797.         sys.modules.setdefault('distutils.command.egg_info', egg_info)
  798.         args = list(args)
  799.         if self.verbose > 2:
  800.             v = 'v' * (self.verbose - 1)
  801.             args.insert(0, '-' + v)
  802.         elif self.verbose < 2:
  803.             args.insert(0, '-q')
  804.         
  805.         if self.dry_run:
  806.             args.insert(0, '-n')
  807.         
  808.         log.info('Running %s %s', setup_script[len(setup_base) + 1:], ' '.join(args))
  809.         
  810.         try:
  811.             run_setup(setup_script, args)
  812.         except SystemExit:
  813.             v = None
  814.             raise DistutilsError('Setup script exited with %s' % (v.args[0],))
  815.  
  816.  
  817.     
  818.     def build_and_install(self, setup_script, setup_base):
  819.         args = [
  820.             'bdist_egg',
  821.             '--dist-dir']
  822.         dist_dir = tempfile.mkdtemp(prefix = 'egg-dist-tmp-', dir = os.path.dirname(setup_script))
  823.         
  824.         try:
  825.             args.append(dist_dir)
  826.             self.run_setup(setup_script, setup_base, args)
  827.             all_eggs = Environment([
  828.                 dist_dir])
  829.             eggs = []
  830.             for key in all_eggs:
  831.                 for dist in all_eggs[key]:
  832.                     eggs.append(self.install_egg(dist.location, setup_base))
  833.                 
  834.             
  835.             if not eggs and not (self.dry_run):
  836.                 log.warn('No eggs found in %s (setup script problem?)', dist_dir)
  837.             
  838.             return eggs
  839.         finally:
  840.             rmtree(dist_dir)
  841.             log.set_verbosity(self.verbose)
  842.  
  843.  
  844.     
  845.     def update_pth(self, dist):
  846.         if self.pth_file is None:
  847.             return None
  848.         for d in self.pth_file[dist.key]:
  849.             if self.multi_version or d.location != dist.location:
  850.                 log.info('Removing %s from easy-install.pth file', d)
  851.                 self.pth_file.remove(d)
  852.                 if d.location in self.shadow_path:
  853.                     self.shadow_path.remove(d.location)
  854.                 
  855.             d.location in self.shadow_path
  856.         
  857.         if not self.dry_run:
  858.             self.pth_file.save()
  859.             if dist.key == 'setuptools':
  860.                 filename = os.path.join(self.install_dir, 'setuptools.pth')
  861.                 if os.path.islink(filename):
  862.                     os.unlink(filename)
  863.                 
  864.                 f = open(filename, 'wt')
  865.                 f.write(self.pth_file.make_relative(dist.location) + '\n')
  866.                 f.close()
  867.             
  868.         
  869.  
  870.     
  871.     def unpack_progress(self, src, dst):
  872.         log.debug('Unpacking %s to %s', src, dst)
  873.         return dst
  874.  
  875.     
  876.     def unpack_and_compile(self, egg_path, destination):
  877.         to_compile = []
  878.         to_chmod = []
  879.         
  880.         def pf(src, dst):
  881.             if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
  882.                 to_compile.append(dst)
  883.                 to_chmod.append(dst)
  884.             elif dst.endswith('.dll') or dst.endswith('.so'):
  885.                 to_chmod.append(dst)
  886.             
  887.             self.unpack_progress(src, dst)
  888.             if not not (self.dry_run) or dst:
  889.                 pass
  890.  
  891.         unpack_archive(egg_path, destination, pf)
  892.         self.byte_compile(to_compile)
  893.         if not self.dry_run:
  894.             for f in to_chmod:
  895.                 mode = (os.stat(f)[stat.ST_MODE] | 365) & 4077
  896.                 chmod(f, mode)
  897.             
  898.         
  899.  
  900.     
  901.     def byte_compile(self, to_compile):
  902.         byte_compile = byte_compile
  903.         import distutils.util
  904.         
  905.         try:
  906.             log.set_verbosity(self.verbose - 1)
  907.             byte_compile(to_compile, optimize = 0, force = 1, dry_run = self.dry_run)
  908.             if self.optimize:
  909.                 byte_compile(to_compile, optimize = self.optimize, force = 1, dry_run = self.dry_run)
  910.         finally:
  911.             log.set_verbosity(self.verbose)
  912.  
  913.  
  914.     
  915.     def no_default_version_msg(self):
  916.         return 'bad install directory or PYTHONPATH\n\nYou are attempting to install a package to a directory that is not\non PYTHONPATH and which Python does not read ".pth" files from.  The\ninstallation directory you specified (via --install-dir, --prefix, or\nthe distutils default setting) was:\n\n    %s\n\nand your PYTHONPATH environment variable currently contains:\n\n    %r\n\nHere are some of your options for correcting the problem:\n\n* You can choose a different installation directory, i.e., one that is\n  on PYTHONPATH or supports .pth files\n\n* You can add the installation directory to the PYTHONPATH environment\n  variable.  (It must then also be on PYTHONPATH whenever you run\n  Python and want to use the package(s) you are installing.)\n\n* You can set up the installation directory to support ".pth" files by\n  using one of the approaches described here:\n\n  http://peak.telecommunity.com/EasyInstall.html#custom-installation-locations\n\nPlease make the appropriate changes for your system and try again.' % (self.install_dir, os.environ.get('PYTHONPATH', ''))
  917.  
  918.     
  919.     def install_site_py(self):
  920.         if self.sitepy_installed:
  921.             return None
  922.         sitepy = os.path.join(self.install_dir, 'site.py')
  923.         source = resource_string(Requirement.parse('setuptools'), 'site.py')
  924.         current = ''
  925.         if os.path.exists(sitepy):
  926.             log.debug('Checking existing site.py in %s', self.install_dir)
  927.             current = open(sitepy, 'rb').read()
  928.             if not current.startswith('def __boot():'):
  929.                 raise DistutilsError('%s is not a setuptools-generated site.py; please remove it.' % sitepy)
  930.             current.startswith('def __boot():')
  931.         
  932.         if current != source:
  933.             log.info('Creating %s', sitepy)
  934.             if not self.dry_run:
  935.                 ensure_directory(sitepy)
  936.                 f = open(sitepy, 'wb')
  937.                 f.write(source)
  938.                 f.close()
  939.             
  940.             self.byte_compile([
  941.                 sitepy])
  942.         
  943.         self.sitepy_installed = True
  944.  
  945.     INSTALL_SCHEMES = dict(posix = dict(install_dir = '$base/lib/python$py_version_short/site-packages', script_dir = '$base/bin'))
  946.     DEFAULT_SCHEME = dict(install_dir = '$base/Lib/site-packages', script_dir = '$base/Scripts')
  947.     
  948.     def _expand(self, *attrs):
  949.         config_vars = self.get_finalized_command('install').config_vars
  950.         if self.prefix:
  951.             config_vars = config_vars.copy()
  952.             config_vars['base'] = self.prefix
  953.             scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
  954.             for attr, val in scheme.items():
  955.                 if getattr(self, attr, None) is None:
  956.                     setattr(self, attr, val)
  957.                     continue
  958.             
  959.         
  960.         subst_vars = subst_vars
  961.         import distutils.util
  962.         for attr in attrs:
  963.             val = getattr(self, attr)
  964.             if val is not None:
  965.                 val = subst_vars(val, config_vars)
  966.                 if os.name == 'posix':
  967.                     val = os.path.expanduser(val)
  968.                 
  969.                 setattr(self, attr, val)
  970.                 continue
  971.         
  972.  
  973.  
  974.  
  975. def get_site_dirs():
  976.     sitedirs = filter(None, os.environ.get('PYTHONPATH', '').split(os.pathsep))
  977.     prefixes = [
  978.         sys.prefix]
  979.     if sys.exec_prefix != sys.prefix:
  980.         prefixes.append(sys.exec_prefix)
  981.     
  982.     for prefix in prefixes:
  983.         if prefix:
  984.             if sys.platform in ('os2emx', 'riscos'):
  985.                 sitedirs.append(os.path.join(prefix, 'Lib', 'site-packages'))
  986.             elif os.sep == '/':
  987.                 sitedirs.extend([
  988.                     os.path.join(prefix, 'lib', 'python' + sys.version[:3], 'site-packages'),
  989.                     os.path.join(prefix, 'lib', 'site-python')])
  990.             else:
  991.                 sitedirs.extend([
  992.                     prefix,
  993.                     os.path.join(prefix, 'lib', 'site-packages')])
  994.             if sys.platform == 'darwin':
  995.                 if 'Python.framework' in prefix:
  996.                     home = os.environ.get('HOME')
  997.                     if home:
  998.                         sitedirs.append(os.path.join(home, 'Library', 'Python', sys.version[:3], 'site-packages'))
  999.                     
  1000.                 
  1001.             
  1002.         sys.platform == 'darwin'
  1003.     
  1004.     for plat_specific in (0, 1):
  1005.         site_lib = get_python_lib(plat_specific)
  1006.         if site_lib not in sitedirs:
  1007.             sitedirs.append(site_lib)
  1008.             continue
  1009.     
  1010.     sitedirs = map(normalize_path, sitedirs)
  1011.     return sitedirs
  1012.  
  1013.  
  1014. def expand_paths(inputs):
  1015.     seen = { }
  1016.     for dirname in inputs:
  1017.         dirname = normalize_path(dirname)
  1018.         if dirname in seen:
  1019.             continue
  1020.         
  1021.         seen[dirname] = 1
  1022.         if not os.path.isdir(dirname):
  1023.             continue
  1024.         
  1025.         files = os.listdir(dirname)
  1026.         yield (dirname, files)
  1027.         for name in files:
  1028.             if not name.endswith('.pth'):
  1029.                 continue
  1030.             
  1031.             if name in ('easy-install.pth', 'setuptools.pth'):
  1032.                 continue
  1033.             
  1034.             f = open(os.path.join(dirname, name))
  1035.             lines = list(yield_lines(f))
  1036.             f.close()
  1037.             for line in lines:
  1038.                 if not line.startswith('import'):
  1039.                     line = normalize_path(line.rstrip())
  1040.                     if line not in seen:
  1041.                         seen[line] = 1
  1042.                         if not os.path.isdir(line):
  1043.                             continue
  1044.                         
  1045.                         yield (line, os.listdir(line))
  1046.                     
  1047.                 line not in seen
  1048.             
  1049.         
  1050.     
  1051.  
  1052.  
  1053. def extract_wininst_cfg(dist_filename):
  1054.     f = open(dist_filename, 'rb')
  1055.     
  1056.     try:
  1057.         endrec = zipfile._EndRecData(f)
  1058.         if endrec is None:
  1059.             return None
  1060.         prepended = endrec[9] - endrec[5] - endrec[6]
  1061.         if prepended < 12:
  1062.             return None
  1063.         f.seek(prepended - 12)
  1064.         import struct
  1065.         import StringIO
  1066.         import ConfigParser
  1067.         (tag, cfglen, bmlen) = struct.unpack('<iii', f.read(12))
  1068.         if tag not in (305419898, 305419899):
  1069.             return None
  1070.         f.seek(prepended - (12 + cfglen))
  1071.         cfg = ConfigParser.RawConfigParser({
  1072.             'version': '',
  1073.             'target_version': '' })
  1074.         
  1075.         try:
  1076.             cfg.readfp(StringIO.StringIO(f.read(cfglen).split(chr(0), 1)[0]))
  1077.         except ConfigParser.Error:
  1078.             tag not in (305419898, 305419899)
  1079.             tag not in (305419898, 305419899)
  1080.             prepended < 12
  1081.             return None
  1082.             endrec is None
  1083.  
  1084.         if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
  1085.             return None
  1086.         return cfg
  1087.     finally:
  1088.         f.close()
  1089.  
  1090.  
  1091.  
  1092. def get_exe_prefixes(exe_filename):
  1093.     prefixes = [
  1094.         ('PURELIB/', ''),
  1095.         ('PLATLIB/pywin32_system32', ''),
  1096.         ('PLATLIB/', ''),
  1097.         ('SCRIPTS/', 'EGG-INFO/scripts/')]
  1098.     z = zipfile.ZipFile(exe_filename)
  1099.     
  1100.     try:
  1101.         for info in z.infolist():
  1102.             name = info.filename
  1103.             parts = name.split('/')
  1104.             if len(parts) == 3 and parts[2] == 'PKG-INFO':
  1105.                 if parts[1].endswith('.egg-info'):
  1106.                     prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
  1107.                     break
  1108.                 
  1109.             
  1110.             if len(parts) != 2 or not name.endswith('.pth'):
  1111.                 continue
  1112.             
  1113.             if name.endswith('-nspkg.pth'):
  1114.                 continue
  1115.             
  1116.             if parts[0].upper() in ('PURELIB', 'PLATLIB'):
  1117.                 for pth in yield_lines(z.read(name)):
  1118.                     pth = pth.strip().replace('\\', '/')
  1119.                     if not pth.startswith('import'):
  1120.                         prefixes.append(('%s/%s/' % (parts[0], pth), ''))
  1121.                         continue
  1122.                 
  1123.     finally:
  1124.         z.close()
  1125.  
  1126.     prefixes = [ (x.lower(), y) for x, y in prefixes ]
  1127.     prefixes.sort()
  1128.     prefixes.reverse()
  1129.     return prefixes
  1130.  
  1131.  
  1132. def parse_requirement_arg(spec):
  1133.     
  1134.     try:
  1135.         return Requirement.parse(spec)
  1136.     except ValueError:
  1137.         raise DistutilsError('Not a URL, existing file, or requirement spec: %r' % (spec,))
  1138.  
  1139.  
  1140.  
  1141. class PthDistributions(Environment):
  1142.     dirty = False
  1143.     
  1144.     def __init__(self, filename, sitedirs = ()):
  1145.         self.filename = filename
  1146.         self.sitedirs = map(normalize_path, sitedirs)
  1147.         self.basedir = normalize_path(os.path.dirname(self.filename))
  1148.         self._load()
  1149.         Environment.__init__(self, [], None, None)
  1150.         for path in yield_lines(self.paths):
  1151.             map(self.add, find_distributions(path, True))
  1152.         
  1153.  
  1154.     
  1155.     def _load(self):
  1156.         self.paths = []
  1157.         saw_import = False
  1158.         seen = dict.fromkeys(self.sitedirs)
  1159.         if os.path.isfile(self.filename):
  1160.             for line in open(self.filename, 'rt'):
  1161.                 if line.startswith('import'):
  1162.                     saw_import = True
  1163.                     continue
  1164.                 
  1165.                 path = line.rstrip()
  1166.                 self.paths.append(path)
  1167.                 if not path.strip() or path.strip().startswith('#'):
  1168.                     continue
  1169.                 
  1170.                 path = self.paths[-1] = normalize_path(os.path.join(self.basedir, path))
  1171.                 if not os.path.exists(path) or path in seen:
  1172.                     self.paths.pop()
  1173.                     self.dirty = True
  1174.                     continue
  1175.                 
  1176.                 seen[path] = 1
  1177.             
  1178.         
  1179.         if self.paths and not saw_import:
  1180.             self.dirty = True
  1181.         
  1182.         while self.paths and not self.paths[-1].strip():
  1183.             self.paths.pop()
  1184.  
  1185.     
  1186.     def save(self):
  1187.         if not self.dirty:
  1188.             return None
  1189.         data = '\n'.join(map(self.make_relative, self.paths))
  1190.         if data:
  1191.             log.debug('Saving %s', self.filename)
  1192.             data = "import sys; sys.__plen = len(sys.path)\n%s\nimport sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)\n" % data
  1193.             if os.path.islink(self.filename):
  1194.                 os.unlink(self.filename)
  1195.             
  1196.             f = open(self.filename, 'wb')
  1197.             f.write(data)
  1198.             f.close()
  1199.         elif os.path.exists(self.filename):
  1200.             log.debug('Deleting empty %s', self.filename)
  1201.             os.unlink(self.filename)
  1202.         
  1203.         self.dirty = False
  1204.  
  1205.     
  1206.     def add(self, dist):
  1207.         if dist.location not in self.paths and dist.location not in self.sitedirs:
  1208.             self.paths.append(dist.location)
  1209.             self.dirty = True
  1210.         
  1211.         Environment.add(self, dist)
  1212.  
  1213.     
  1214.     def remove(self, dist):
  1215.         while dist.location in self.paths:
  1216.             self.paths.remove(dist.location)
  1217.             self.dirty = True
  1218.         Environment.remove(self, dist)
  1219.  
  1220.     
  1221.     def make_relative(self, path):
  1222.         (npath, last) = os.path.split(normalize_path(path))
  1223.         baselen = len(self.basedir)
  1224.         parts = [
  1225.             last]
  1226.         if not os.altsep == '/' or '/':
  1227.             pass
  1228.         sep = os.sep
  1229.         while len(npath) >= baselen:
  1230.             if npath == self.basedir:
  1231.                 parts.append(os.curdir)
  1232.                 parts.reverse()
  1233.                 return sep.join(parts)
  1234.             (npath, last) = os.path.split(npath)
  1235.             parts.append(last)
  1236.             continue
  1237.             npath == self.basedir
  1238.         return path
  1239.  
  1240.  
  1241.  
  1242. def get_script_header(script_text, executable = sys_executable, wininst = False):
  1243.     first_line_re = first_line_re
  1244.     import distutils.command.build_scripts
  1245.     first = (script_text + '\n').splitlines()[0]
  1246.     match = first_line_re.match(first)
  1247.     options = ''
  1248.     if match:
  1249.         if not match.group(1):
  1250.             pass
  1251.         options = ''
  1252.         if options:
  1253.             options = ' ' + options
  1254.         
  1255.     
  1256.     if wininst:
  1257.         executable = 'python.exe'
  1258.     else:
  1259.         executable = nt_quote_arg(executable)
  1260.     hdr = '#!%(executable)s%(options)s\n' % locals()
  1261.     if unicode(hdr, 'ascii', 'ignore').encode('ascii') != hdr:
  1262.         if options:
  1263.             if options.strip().startswith('-'):
  1264.                 options = ' -x' + options.strip()[1:]
  1265.             
  1266.         else:
  1267.             options = ' -x'
  1268.     
  1269.     executable = fix_jython_executable(executable, options)
  1270.     hdr = '#!%(executable)s%(options)s\n' % locals()
  1271.     return hdr
  1272.  
  1273.  
  1274. def auto_chmod(func, arg, exc):
  1275.     if func is os.remove and os.name == 'nt':
  1276.         chmod(arg, stat.S_IWRITE)
  1277.         return func(arg)
  1278.     exc = sys.exc_info()
  1279.     raise exc[0], (exc[1][0], exc[1][1] + ' %s %s' % (func, arg))
  1280.  
  1281.  
  1282. def uncache_zipdir(path):
  1283.     zdc = _zip_directory_cache
  1284.     import zipimport
  1285.     _uncache(path, zdc)
  1286.     _uncache(path, sys.path_importer_cache)
  1287.  
  1288.  
  1289. def _uncache(path, cache):
  1290.     pass
  1291.  
  1292.  
  1293. def is_python(text, filename = '<string>'):
  1294.     
  1295.     try:
  1296.         compile(text, filename, 'exec')
  1297.     except (SyntaxError, TypeError):
  1298.         return False
  1299.  
  1300.     return True
  1301.  
  1302.  
  1303. def is_sh(executable):
  1304.     
  1305.     try:
  1306.         fp = open(executable)
  1307.         magic = fp.read(2)
  1308.         fp.close()
  1309.     except (OSError, IOError):
  1310.         return executable
  1311.  
  1312.     return magic == '#!'
  1313.  
  1314.  
  1315. def nt_quote_arg(arg):
  1316.     result = []
  1317.     needquote = False
  1318.     nb = 0
  1319.     if not ' ' in arg:
  1320.         pass
  1321.     needquote = '\t' in arg
  1322.     if needquote:
  1323.         result.append('"')
  1324.     
  1325.     for c in arg:
  1326.         if c == '\\':
  1327.             nb += 1
  1328.             continue
  1329.         if c == '"':
  1330.             result.append('\\' * nb * 2 + '\\"')
  1331.             nb = 0
  1332.             continue
  1333.         if nb:
  1334.             result.append('\\' * nb)
  1335.             nb = 0
  1336.         
  1337.         result.append(c)
  1338.     
  1339.     if nb:
  1340.         result.append('\\' * nb)
  1341.     
  1342.     if needquote:
  1343.         result.append('\\' * nb)
  1344.         result.append('"')
  1345.     
  1346.     return ''.join(result)
  1347.  
  1348.  
  1349. def is_python_script(script_text, filename):
  1350.     if filename.endswith('.py') or filename.endswith('.pyw'):
  1351.         return True
  1352.     if is_python(script_text, filename):
  1353.         return True
  1354.     if script_text.startswith('#!'):
  1355.         return 'python' in script_text.splitlines()[0].lower()
  1356.     return False
  1357.  
  1358.  
  1359. try:
  1360.     from os import chmod as _chmod
  1361. except ImportError:
  1362.     
  1363.     def _chmod(*args):
  1364.         pass
  1365.  
  1366.  
  1367.  
  1368. def chmod(path, mode):
  1369.     log.debug('changing mode of %s to %o', path, mode)
  1370.     
  1371.     try:
  1372.         _chmod(path, mode)
  1373.     except os.error:
  1374.         e = None
  1375.         log.debug('chmod failed: %s', e)
  1376.  
  1377.  
  1378.  
  1379. def fix_jython_executable(executable, options):
  1380.     if sys.platform.startswith('java') and is_sh(executable):
  1381.         if options:
  1382.             log.warn('WARNING: Unable to adapt shebang line for Jython, the following script is NOT executable\n         see http://bugs.jython.org/issue1112 for more information.')
  1383.         else:
  1384.             return '/usr/bin/env %s' % executable
  1385.     options
  1386.     return executable
  1387.  
  1388.  
  1389. def get_script_args(dist, executable = sys_executable, wininst = False):
  1390.     spec = str(dist.as_requirement())
  1391.     header = get_script_header('', executable, wininst)
  1392.     for group in ('console_scripts', 'gui_scripts'):
  1393.         for name, ep in dist.get_entry_map(group).items():
  1394.             script_text = '# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\n__requires__ = %(spec)r\nimport sys\nfrom pkg_resources import load_entry_point\n\nsys.exit(\n   load_entry_point(%(spec)r, %(group)r, %(name)r)()\n)\n' % locals()
  1395.             if sys.platform == 'win32' or wininst:
  1396.                 if group == 'gui_scripts':
  1397.                     (ext, launcher) = ('-script.pyw', 'gui.exe')
  1398.                     old = [
  1399.                         '.pyw']
  1400.                     new_header = re.sub('(?i)python.exe', 'pythonw.exe', header)
  1401.                 else:
  1402.                     (ext, launcher) = ('-script.py', 'cli.exe')
  1403.                     old = [
  1404.                         '.py',
  1405.                         '.pyc',
  1406.                         '.pyo']
  1407.                     new_header = re.sub('(?i)pythonw.exe', 'python.exe', header)
  1408.                 if os.path.exists(new_header[2:-1]) or sys.platform != 'win32':
  1409.                     hdr = new_header
  1410.                 else:
  1411.                     hdr = header
  1412.                 yield ('t', [], [], [ name + x for x in old ])
  1413.                 hdr + script_text
  1414.                 yield (name + '.exe', resource_string('setuptools', launcher), 'b')
  1415.                 name + ext
  1416.                 continue
  1417.             yield (name, header + script_text)
  1418.         
  1419.     
  1420.  
  1421.  
  1422. def rmtree(path, ignore_errors = False, onerror = auto_chmod):
  1423.     if ignore_errors:
  1424.         
  1425.         def onerror(*args):
  1426.             pass
  1427.  
  1428.     elif onerror is None:
  1429.         
  1430.         def onerror(*args):
  1431.             raise 
  1432.  
  1433.     
  1434.     names = []
  1435.     
  1436.     try:
  1437.         names = os.listdir(path)
  1438.     except os.error:
  1439.         err = None
  1440.         onerror(os.listdir, path, sys.exc_info())
  1441.  
  1442.     for name in names:
  1443.         fullname = os.path.join(path, name)
  1444.         
  1445.         try:
  1446.             mode = os.lstat(fullname).st_mode
  1447.         except os.error:
  1448.             mode = 0
  1449.  
  1450.         if stat.S_ISDIR(mode):
  1451.             rmtree(fullname, ignore_errors, onerror)
  1452.             continue
  1453.         
  1454.         try:
  1455.             os.remove(fullname)
  1456.         continue
  1457.         except os.error:
  1458.             err = None
  1459.             onerror(os.remove, fullname, sys.exc_info())
  1460.             continue
  1461.         
  1462.  
  1463.     
  1464.     
  1465.     try:
  1466.         os.rmdir(path)
  1467.     except os.error:
  1468.         None<EXCEPTION MATCH>os.error
  1469.         None<EXCEPTION MATCH>os.error
  1470.         onerror(os.rmdir, path, sys.exc_info())
  1471.     except:
  1472.         None<EXCEPTION MATCH>os.error
  1473.  
  1474.  
  1475.  
  1476. def bootstrap():
  1477.     import setuptools
  1478.     argv0 = os.path.dirname(setuptools.__path__[0])
  1479.     sys.argv[0] = argv0
  1480.     sys.argv.append(argv0)
  1481.     main()
  1482.  
  1483.  
  1484. def main(argv = None, **kw):
  1485.     setup = setup
  1486.     import setuptools
  1487.     Distribution = Distribution
  1488.     import setuptools.dist
  1489.     import distutils.core as distutils
  1490.     USAGE = 'usage: %(script)s [options] requirement_or_url ...\n   or: %(script)s --help\n'
  1491.     
  1492.     def gen_usage(script_name):
  1493.         script = os.path.basename(script_name)
  1494.         return USAGE % vars()
  1495.  
  1496.     
  1497.     def with_ei_usage(f):
  1498.         old_gen_usage = distutils.core.gen_usage
  1499.         
  1500.         try:
  1501.             distutils.core.gen_usage = gen_usage
  1502.             return f()
  1503.         finally:
  1504.             distutils.core.gen_usage = old_gen_usage
  1505.  
  1506.  
  1507.     
  1508.     class DistributionWithoutHelpCommands('DistributionWithoutHelpCommands', (Distribution,)):
  1509.         common_usage = ''
  1510.         
  1511.         def _show_help(self, *args, **kw):
  1512.             (None, None, None, with_ei_usage)((lambda : Distribution._show_help(self, *args, **kw)))
  1513.  
  1514.  
  1515.     if argv is None:
  1516.         argv = sys.argv[1:]
  1517.     
  1518.     (None, None, None, with_ei_usage)((lambda : if not sys.argv[0]:
  1519. passsetup(script_args = [
  1520. '-q',
  1521. 'easy_install',
  1522. '-v'] + argv, script_name = 'easy_install', distclass = DistributionWithoutHelpCommands, **kw)))
  1523.  
  1524.