virtualenv/res/lib/lib_create_env.py
changeset 0 81e7900b06a7
child 2 aaa8629d42c9
equal deleted inserted replaced
-1:000000000000 0:81e7900b06a7
       
     1 import sys
       
     2 import os
       
     3 import os.path
       
     4 import shutil
       
     5 import tarfile
       
     6 import zipfile
       
     7 import urllib
       
     8 import platform
       
     9 import patch
       
    10 import struct
       
    11 import glob
       
    12 import re
       
    13 
       
    14 join = os.path.join
       
    15 system_str = platform.system()
       
    16 
       
    17 URLS = {
       
    18     #'': {'setup': '', 'url':'', 'local':''},
       
    19     'DISTRIBUTE': {'setup': 'distribute', 'url':'http://pypi.python.org/packages/source/d/distribute/distribute-0.6.34.tar.gz', 'local':"distribute-0.6.34.tar.gz", 'install': {'method': 'pip', 'option_str': None, 'dict_extra_env': None}},
       
    20     'DJANGO': {'setup': 'django', 'url': 'https://github.com/IRI-Research/django/archive/698eff4a5da55a1b5a8b4ecddab2b2a85854d4da.tar.gz', 'local':"Django-1.5.2.dev20130524113953.tar.gz", 'install': {'method': 'pip', 'option_str': None, 'dict_extra_env': None}},
       
    21     'SIX' : {'setup':'six', 'url':'https://pypi.python.org/packages/source/s/six/six-1.3.0.tar.gz', 'local': 'six-1.3.0.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    22     'DJANGO-EXTENSIONS': { 'setup': 'django-extensions', 'url':'https://github.com/django-extensions/django-extensions/archive/1.1.1.tar.gz', 'local':"django-extensions-1.1.1.tar.gz", 'install': {'method': 'pip', 'option_str': None, 'dict_extra_env': None}},
       
    23     'SOUTH': { 'setup': 'South', 'url':'http://www.aeracode.org/releases/south/south-0.7.6.tar.gz', 'local':"south-0.7.6.tar.gz", 'install': {'method': 'pip', 'option_str': None, 'dict_extra_env': None}},
       
    24     'RDFLIB' : {'setup':'rdflib', 'url':'https://github.com/RDFLib/rdflib/archive/4.0.1.tar.gz', 'local': 'rdflib-4.0.1.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    25     'REQUESTS': {'setup': 'requests', 'url':'https://github.com/kennethreitz/requests/archive/v1.2.3.tar.gz', 'local':'requests-1.2.3.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    26     'SIMPLEJSON': {'setup': 'simplejson','url':'https://github.com/simplejson/simplejson/archive/v3.3.0.tar.gz', 'local': 'simplejson-3.3.0.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    27     'ISODATE': {'setup': 'isodate','url':'https://pypi.python.org/packages/source/i/isodate/isodate-0.4.9.tar.gz', 'local': 'isodate-0.4.9.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    28     'PYPARSING': {'setup': 'pyparsing','url':'http://downloads.sourceforge.net/project/pyparsing/pyparsing/pyparsing-1.5.7/pyparsing-1.5.7.tar.gz', 'local': 'pyparsing-1.5.7.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    29     'SPARQLWRAPPER': {'setup': 'sparqlwrapper','url':'http://downloads.sourceforge.net/project/sparql-wrapper/sparql-wrapper-python/1.5.2/SPARQLWrapper-1.5.2.tar.gz', 'local': 'SPARQLWrapper-1.5.2.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    30     'HTML5LIB': {'setup': 'html5lib','url':'https://github.com/html5lib/html5lib-python/archive/1.0b1.tar.gz', 'local': 'html5lib-python-1.0b1.tar.gz', 'install' : {'method':'pip', 'option_str': None, 'dict_extra_env': None}},
       
    31     'PSYCOPG2': {'setup': 'psycopg2','url': 'http://initd.org/psycopg/tarballs/PSYCOPG-2-5/psycopg2-2.5.tar.gz', 'local':"psycopg2-2.5.tar.gz", 'install': {'method': 'pip', 'option_str': None, 'dict_extra_env': None}},
       
    32 }
       
    33 
       
    34 class ResourcesEnv(object):
       
    35 
       
    36     def __init__(self, src_base, urls, normal_installs):
       
    37         self.src_base = src_base
       
    38         self.URLS = {}
       
    39         self.__init_url(urls)
       
    40         self.NORMAL_INSTALL = normal_installs
       
    41 
       
    42     def get_src_base_path(self, fpath):
       
    43         return os.path.abspath(os.path.join(self.src_base, fpath)).replace("\\","/")
       
    44     
       
    45     def __add_package_def(self, key, dict):
       
    46         self.URLS[key] = dict
       
    47         
       
    48     def __init_url(self, urls):
       
    49         for key, url_dict in urls.items():
       
    50             url_dict_copy = url_dict.copy()
       
    51             if not url_dict['url'].startswith("http://"):
       
    52                 url_dict_copy['url'] = self.get_src_base_path(url_dict['url'])
       
    53             url_dict_copy['local'] = self.get_src_base_path(url_dict['local'])            
       
    54             
       
    55             self.__add_package_def(key, url_dict_copy )
       
    56 
       
    57 def ensure_dir(dir, logger):
       
    58     logger.notify('Check directory %s' % dir)
       
    59     if not os.path.exists(dir):
       
    60         logger.notify('Creating directory %s' % dir)
       
    61         os.makedirs(dir)
       
    62 
       
    63 def extend_parser(parser):    
       
    64     parser.add_option(
       
    65         '--index-url',
       
    66         metavar='INDEX_URL',
       
    67         dest='index_url',
       
    68         default='http://pypi.python.org/simple/',
       
    69         help='base URL of Python Package Index')
       
    70     parser.add_option(
       
    71         '--type-install',
       
    72         metavar='type_install',
       
    73         dest='type_install',
       
    74         help='type install : local, url, setup - default : local')
       
    75     parser.add_option(
       
    76         '--ignore-packages',
       
    77         metavar='ignore_packages',
       
    78         dest='ignore_packages',
       
    79         default=None,
       
    80         help='list of comma separated keys for package to ignore')    
       
    81 
       
    82 def install_psycopg2(option_str, extra_env, res_source_key, home_dir, lib_dir, tmp_dir, src_dir, res_env, logger, call_subprocess, filter_python_develop):
       
    83     psycopg2_src = os.path.join(src_dir,"psycopg2.zip")
       
    84     shutil.copy(res_env.URLS['PSYCOPG2'][res_source_key], psycopg2_src)
       
    85     #extract psycopg2
       
    86     zf = zipfile.ZipFile(psycopg2_src)
       
    87     psycopg2_base_path = os.path.join(src_dir,"psycopg2")
       
    88     zf.extractall(psycopg2_base_path)
       
    89     zf.close()
       
    90     
       
    91     psycopg2_src_path = os.path.join(psycopg2_base_path, os.listdir(psycopg2_base_path)[0])
       
    92     shutil.copytree(os.path.join(psycopg2_src_path, 'psycopg2'), os.path.abspath(os.path.join(home_dir, 'Lib/site-packages', 'psycopg2')))
       
    93     shutil.copy(os.path.join(psycopg2_src_path, 'psycopg2-2.4.5-py2.7.egg-info'), os.path.abspath(os.path.join(home_dir, 'Lib/site-packages', 'site-packages')))
       
    94     
       
    95 
       
    96 def install_mysql(option_str, extra_env, res_source_key, home_dir, lib_dir, tmp_dir, src_dir, res_env, logger, call_subprocess, filter_python_develop):
       
    97     
       
    98     args = [os.path.abspath(os.path.join(home_dir, 'bin', 'pip')), 'install', res_env.URLS['MYSQL'][res_source_key]]                
       
    99     if option_str :
       
   100         args.insert(4,option_str)
       
   101     call_subprocess(args,
       
   102             cwd=os.path.abspath(tmp_dir),
       
   103             filter_stdout=filter_python_develop,
       
   104             show_stdout=True,
       
   105             extra_env=extra_env)
       
   106 
       
   107     mysqlconfig_output = []
       
   108     
       
   109     call_subprocess(['mysql_config', '--libmysqld-libs'],
       
   110         cwd=os.path.abspath(tmp_dir),
       
   111         filter_stdout=lambda line: mysqlconfig_output.append(line),
       
   112         show_stdout=True)
       
   113         
       
   114     mysqlconfig_output = "".join(mysqlconfig_output)
       
   115     m = re.search("\-L[\'\"]?([\w\/]+)[\'\"]?", mysqlconfig_output)
       
   116     if m:
       
   117         repdylibpath = m.group(1)
       
   118     else:
       
   119         repdylibpath = '/usr/local/mysql/lib'
       
   120         
       
   121     dyliblist = glob.glob(repdylibpath+"/libmysqlclient.*.dylib")
       
   122     def key_func(s):
       
   123         m = re.match(repdylibpath+"/libmysqlclient\.([\d]+)\.dylib", s)
       
   124         if m:
       
   125             return int(m.group(1))
       
   126         else:
       
   127             return sys.maxint
       
   128     dyliblist.sort(key=key_func)
       
   129     
       
   130     if dyliblist:
       
   131         dylibpath = dyliblist[0]
       
   132     else:
       
   133         dylibpath = '/usr/local/mysql/lib/libmysqlclient.18.dylib'
       
   134         
       
   135     dylibname = os.path.basename(dylibpath)    
       
   136     sopath = os.path.join(os.path.abspath(lib_dir), 'site-packages', '_mysql.so')
       
   137     
       
   138     call_subprocess(['install_name_tool', '-change', dylibname, dylibpath, sopath],
       
   139         cwd=os.path.abspath(tmp_dir),
       
   140         filter_stdout=filter_python_develop,
       
   141         show_stdout=True)
       
   142 
       
   143 
       
   144 def gen_install_comp_lib(lib_name, lib_key, configure_options=[]):
       
   145     
       
   146     def install_lib(option_str, extra_env, res_source_key, home_dir, lib_dir, tmp_dir, src_dir, res_env, logger, call_subprocess, filter_python_develop):
       
   147         lib_src = os.path.join(src_dir,lib_name+".tar.gz")
       
   148         logger.notify("Copy %s to %s " % (res_env.URLS[lib_key][res_source_key],lib_src))
       
   149         shutil.copy(res_env.URLS[lib_key][res_source_key], lib_src)
       
   150         tf = tarfile.open(lib_src,'r:gz')
       
   151         lib_base_path = os.path.join(src_dir, lib_name) 
       
   152         logger.notify("Extract %s to %s " % (lib_name,lib_base_path))
       
   153         tf.extractall(lib_base_path)
       
   154         tf.close()
       
   155         
       
   156         lib_src_path = os.path.join(lib_base_path, os.listdir(lib_base_path)[0])
       
   157     
       
   158         logger.notify(lib_name + " configure in " + lib_src_path)
       
   159         call_subprocess(['./configure', '--prefix='+os.path.abspath(home_dir)] + configure_options,
       
   160                         cwd=os.path.abspath(lib_src_path),
       
   161                         filter_stdout=filter_python_develop,
       
   162                         show_stdout=True)
       
   163         
       
   164         logger.notify(lib_name + " make in " + lib_src_path)
       
   165         call_subprocess(['make'],
       
   166                         cwd=os.path.abspath(lib_src_path),
       
   167                         filter_stdout=filter_python_develop,
       
   168                         show_stdout=True)
       
   169     
       
   170         logger.notify(lib_name + "make install in " + lib_src_path)
       
   171         call_subprocess(['make', 'install'],
       
   172                         cwd=os.path.abspath(lib_src_path),
       
   173                         filter_stdout=filter_python_develop,
       
   174                         show_stdout=True)
       
   175     return install_lib
       
   176 
       
   177 install_libjpeg = gen_install_comp_lib("libjpeg", "LIBJPEG", ['--enable-shared'])
       
   178 install_zlib = gen_install_comp_lib("zlib", "ZLIB", [])
       
   179     
       
   180 
       
   181 def lib_generate_install_methods(path_locations, src_base, Logger, call_subprocess, normal_installs, options_to_add=None, urls= None):
       
   182     
       
   183     all_urls = URLS.copy()
       
   184     if urls is not None:
       
   185         all_urls.update(urls)
       
   186         
       
   187     res_env = ResourcesEnv(src_base, all_urls, normal_installs)
       
   188 
       
   189     def filter_python_develop(line):
       
   190         if not line.strip():
       
   191             return Logger.DEBUG
       
   192         for prefix in ['Searching for', 'Reading ', 'Best match: ', 'Processing ',
       
   193                        'Moving ', 'Adding ', 'running ', 'writing ', 'Creating ',
       
   194                        'creating ', 'Copying ']:
       
   195             if line.startswith(prefix):
       
   196                 return Logger.DEBUG
       
   197         return Logger.NOTIFY
       
   198     
       
   199     
       
   200     def normal_install(key, method, option_str, extra_env, res_source_key, home_dir, tmp_dir, res_env, logger, call_subprocess):
       
   201         logger.notify("Install %s from %s with %s" % (key,res_env.URLS[key][res_source_key],method))
       
   202         if method == 'pip':
       
   203             if sys.platform == 'win32':
       
   204                 args = [os.path.abspath(os.path.join(home_dir, 'Scripts', 'pip')), 'install', res_env.URLS[key][res_source_key]]
       
   205             else:
       
   206                 args = [os.path.abspath(os.path.join(home_dir, 'bin', 'pip')), 'install', res_env.URLS[key][res_source_key]]
       
   207             if option_str :
       
   208                 args.insert(4,option_str)
       
   209             if key == 'local':
       
   210                 if extra_env is None:
       
   211                     extra_env = {}
       
   212                 extra_env.append("PIP_DOWNLOAD_CACHE", res_env.get_src_base_path(""))
       
   213             call_subprocess(args,
       
   214                     cwd=os.path.abspath(tmp_dir),
       
   215                     filter_stdout=filter_python_develop,
       
   216                     show_stdout=True,
       
   217                     extra_env=extra_env)
       
   218         else:
       
   219             if sys.platform == 'win32':
       
   220                 args = [os.path.abspath(os.path.join(home_dir, 'Scripts', 'easy_install')), res_env.URLS[key][res_source_key]]
       
   221             else:
       
   222                 args = [os.path.abspath(os.path.join(home_dir, 'bin', 'easy_install')), res_env.URLS[key][res_source_key]]
       
   223             if option_str :
       
   224                 args.insert(1,option_str)
       
   225             call_subprocess(args,
       
   226                     cwd=os.path.abspath(tmp_dir),
       
   227                     filter_stdout=filter_python_develop,
       
   228                     show_stdout=True,
       
   229                     extra_env=extra_env)            
       
   230  
       
   231     
       
   232     def after_install(options, home_dir):
       
   233         
       
   234         global logger
       
   235         
       
   236         verbosity = options.verbose - options.quiet
       
   237         logger = Logger([(Logger.level_for_integer(2-verbosity), sys.stdout)])
       
   238 
       
   239         
       
   240         home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
       
   241         base_dir = os.path.dirname(home_dir)
       
   242         src_dir = os.path.join(home_dir, 'src')
       
   243         tmp_dir = os.path.join(home_dir, 'tmp')
       
   244         ensure_dir(src_dir, logger)
       
   245         ensure_dir(tmp_dir, logger)
       
   246         system_str = platform.system()
       
   247                 
       
   248         res_source_key = getattr(options, 'type_install') if hasattr(options, 'type_install') else 'local' #.get('type_install', 'local')
       
   249         if res_source_key is None:
       
   250             res_source_key = 'local'
       
   251         
       
   252         ignore_packages = []
       
   253         
       
   254         if system_str == 'Windows':
       
   255             default_install_options = {'method': 'easy_install', 'option_str': None, 'dict_extra_env': {}}
       
   256         else:
       
   257             default_install_options = {'method': 'pip', 'option_str': None, 'dict_extra_env': {}}
       
   258             
       
   259         if options.ignore_packages :
       
   260             ignore_packages = options.ignore_packages.split(",")
       
   261         
       
   262         logger.indent += 2
       
   263         try:    
       
   264             for key in res_env.NORMAL_INSTALL:
       
   265                 if key not in res_env.URLS:
       
   266                     logger.notify("%s not found in def : passing" % (key,))
       
   267                 install_options = res_env.URLS[key].get('install', None)
       
   268                 if install_options is None:
       
   269                     install_options = default_install_options
       
   270                 method = install_options.get('method', default_install_options['method'])
       
   271                 option_str = install_options.get('option_str', default_install_options['option_str'])
       
   272                 extra_env = install_options.get('dict_extra_env', default_install_options['dict_extra_env'])
       
   273                 if not extra_env:
       
   274                     extra_env = {}
       
   275                     
       
   276                 if 'TMPDIR' not in extra_env:
       
   277                     extra_env['TMPDIR'] = os.path.abspath(tmp_dir)          
       
   278                 #isinstance(lst, (list, tuple))
       
   279                 if key not in ignore_packages:
       
   280                     logger.notify("install %s with method %s" % (key, repr(method)))
       
   281                     if callable(method):
       
   282                         method(option_str, extra_env, res_source_key, home_dir, lib_dir, tmp_dir, src_dir, res_env, logger, call_subprocess, filter_python_develop)
       
   283                     elif method in globals() and callable(globals()[method]) and method not in ['pip', 'easy_install']:  
       
   284                         globals()[method](option_str, extra_env, res_source_key, home_dir, lib_dir, tmp_dir, src_dir, res_env, logger, call_subprocess, filter_python_develop)
       
   285                     else:
       
   286                         normal_install(key, method, option_str, extra_env, res_source_key, home_dir, tmp_dir, res_env, logger, call_subprocess)
       
   287                             
       
   288             logger.notify("Clear source dir")
       
   289             shutil.rmtree(src_dir)
       
   290     
       
   291         finally:
       
   292             logger.indent -= 2
       
   293         script_dir = join(base_dir, bin_dir)
       
   294         logger.notify('Run "%s Package" to install new packages that provide builds'
       
   295                       % join(script_dir, 'easy_install'))
       
   296     
       
   297     def adjust_options(options, args):
       
   298         if not options_to_add:
       
   299             pass
       
   300         for opt in options_to_add:
       
   301             test_opt = opt.split('=',1)[0]
       
   302             #if not hasattr(options,test_opt) or getattr(options, test_opt) is None:
       
   303             setattr(options, test_opt,opt.split('=',1)[1] if "=" in opt else True)
       
   304 
       
   305     return adjust_options, extend_parser, after_install