NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

util.py (10966B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\stdlib\distutils\util.py
      2 __revision__ = '$Id: util.py 87602 2011-01-01 04:24:26Z richard.tew $'
      3 import sys, os, string, re
      4 from distutils.errors import DistutilsPlatformError
      5 from distutils.dep_util import newer
      6 from distutils.spawn import spawn
      7 from distutils import log
      8 from distutils.errors import DistutilsByteCompileError
      9 
     10 def get_platform():
     11     if os.name == 'nt':
     12         prefix = ' bit ('
     13         i = string.find(sys.version, prefix)
     14         if i == -1:
     15             return sys.platform
     16         j = string.find(sys.version, ')', i)
     17         look = sys.version[i + len(prefix):j].lower()
     18         if look == 'amd64':
     19             return 'win-amd64'
     20         if look == 'itanium':
     21             return 'win-ia64'
     22         return sys.platform
     23     if os.name != 'posix' or not hasattr(os, 'uname'):
     24         return sys.platform
     25     osname, host, release, version, machine = os.uname()
     26     osname = string.lower(osname)
     27     osname = string.replace(osname, '/', '')
     28     machine = string.replace(machine, ' ', '_')
     29     machine = string.replace(machine, '/', '-')
     30     if osname[:5] == 'linux':
     31         return '%s-%s' % (osname, machine)
     32     if osname[:5] == 'sunos':
     33         if release[0] >= '5':
     34             osname = 'solaris'
     35             release = '%d.%s' % (int(release[0]) - 3, release[2:])
     36     else:
     37         if osname[:4] == 'irix':
     38             return '%s-%s' % (osname, release)
     39         if osname[:3] == 'aix':
     40             return '%s-%s.%s' % (osname, version, release)
     41         if osname[:6] == 'cygwin':
     42             osname = 'cygwin'
     43             rel_re = re.compile('[\\d.]+')
     44             m = rel_re.match(release)
     45             if m:
     46                 release = m.group()
     47         elif osname[:6] == 'darwin':
     48             from distutils.sysconfig import get_config_vars
     49             cfgvars = get_config_vars()
     50             macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
     51             if not macver:
     52                 macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
     53             macrelease = macver
     54             try:
     55                 f = open('/System/Library/CoreServices/SystemVersion.plist')
     56             except IOError:
     57                 pass
     58             else:
     59                 try:
     60                     m = re.search('<key>ProductUserVisibleVersion</key>\\s*' + '<string>(.*?)</string>', f.read())
     61                     if m is not None:
     62                         macrelease = '.'.join(m.group(1).split('.')[:2])
     63                 finally:
     64                     f.close()
     65 
     66             if not macver:
     67                 macver = macrelease
     68             if macver:
     69                 from distutils.sysconfig import get_config_vars
     70                 release = macver
     71                 osname = 'macosx'
     72                 if macrelease + '.' >= '10.4.' and '-arch' in get_config_vars().get('CFLAGS', '').strip():
     73                     machine = 'fat'
     74                     cflags = get_config_vars().get('CFLAGS')
     75                     archs = re.findall('-arch\\s+(\\S+)', cflags)
     76                     archs = tuple(sorted(set(archs)))
     77                     if len(archs) == 1:
     78                         machine = archs[0]
     79                     elif archs == ('i386', 'ppc'):
     80                         machine = 'fat'
     81                     elif archs == ('i386', 'x86_64'):
     82                         machine = 'intel'
     83                     elif archs == ('i386', 'ppc', 'x86_64'):
     84                         machine = 'fat3'
     85                     elif archs == ('ppc64', 'x86_64'):
     86                         machine = 'fat64'
     87                     elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
     88                         machine = 'universal'
     89                     else:
     90                         raise ValueError("Don't know machine value for archs=%r" % (archs,))
     91                 elif machine == 'i386':
     92                     if sys.maxint >= 4294967296L:
     93                         machine = 'x86_64'
     94                 elif machine in ('PowerPC', 'Power_Macintosh'):
     95                     machine = 'ppc'
     96                     if sys.maxint >= 4294967296L:
     97                         machine = 'ppc64'
     98     return '%s-%s-%s' % (osname, release, machine)
     99 
    100 
    101 def convert_path(pathname):
    102     if os.sep == '/':
    103         return pathname
    104     if not pathname:
    105         return pathname
    106     if pathname[0] == '/':
    107         raise ValueError, "path '%s' cannot be absolute" % pathname
    108     if pathname[-1] == '/':
    109         raise ValueError, "path '%s' cannot end with '/'" % pathname
    110     paths = string.split(pathname, '/')
    111     while '.' in paths:
    112         paths.remove('.')
    113 
    114     if not paths:
    115         return os.curdir
    116     return os.path.join(*paths)
    117 
    118 
    119 def change_root(new_root, pathname):
    120     if os.name == 'posix':
    121         if not os.path.isabs(pathname):
    122             return os.path.join(new_root, pathname)
    123         else:
    124             return os.path.join(new_root, pathname[1:])
    125     else:
    126         if os.name == 'nt':
    127             drive, path = os.path.splitdrive(pathname)
    128             if path[0] == '\\':
    129                 path = path[1:]
    130             return os.path.join(new_root, path)
    131         if os.name == 'os2':
    132             drive, path = os.path.splitdrive(pathname)
    133             if path[0] == os.sep:
    134                 path = path[1:]
    135             return os.path.join(new_root, path)
    136         raise DistutilsPlatformError, "nothing known about platform '%s'" % os.name
    137 
    138 
    139 _environ_checked = 0
    140 
    141 def check_environ():
    142     global _environ_checked
    143     if _environ_checked:
    144         return
    145     if os.name == 'posix' and 'HOME' not in os.environ:
    146         import pwd
    147         os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
    148     if 'PLAT' not in os.environ:
    149         os.environ['PLAT'] = get_platform()
    150     _environ_checked = 1
    151 
    152 
    153 def subst_vars(s, local_vars):
    154     check_environ()
    155 
    156     def _subst(match, local_vars = local_vars):
    157         var_name = match.group(1)
    158         if var_name in local_vars:
    159             return str(local_vars[var_name])
    160         else:
    161             return os.environ[var_name]
    162 
    163     try:
    164         return re.sub('\\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
    165     except KeyError as var:
    166         raise ValueError, "invalid variable '$%s'" % var
    167 
    168 
    169 def grok_environment_error(exc, prefix = 'error: '):
    170     if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
    171         if exc.filename:
    172             error = prefix + '%s: %s' % (exc.filename, exc.strerror)
    173         else:
    174             error = prefix + '%s' % exc.strerror
    175     else:
    176         error = prefix + str(exc[-1])
    177     return error
    178 
    179 
    180 _wordchars_re = _squote_re = _dquote_re = None
    181 
    182 def _init_regex():
    183     global _dquote_re
    184     global _squote_re
    185     global _wordchars_re
    186     _wordchars_re = re.compile('[^\\\\\\\'\\"%s ]*' % string.whitespace)
    187     _squote_re = re.compile("'(?:[^'\\\\]|\\\\.)*'")
    188     _dquote_re = re.compile('"(?:[^"\\\\]|\\\\.)*"')
    189 
    190 
    191 def split_quoted(s):
    192     if _wordchars_re is None:
    193         _init_regex()
    194     s = string.strip(s)
    195     words = []
    196     pos = 0
    197     while s:
    198         m = _wordchars_re.match(s, pos)
    199         end = m.end()
    200         if end == len(s):
    201             words.append(s[:end])
    202             break
    203         if s[end] in string.whitespace:
    204             words.append(s[:end])
    205             s = string.lstrip(s[end:])
    206             pos = 0
    207         elif s[end] == '\\':
    208             s = s[:end] + s[end + 1:]
    209             pos = end + 1
    210         else:
    211             if s[end] == "'":
    212                 m = _squote_re.match(s, end)
    213             elif s[end] == '"':
    214                 m = _dquote_re.match(s, end)
    215             else:
    216                 raise RuntimeError, "this can't happen (bad char '%c')" % s[end]
    217             if m is None:
    218                 raise ValueError, 'bad string (mismatched %s quotes?)' % s[end]
    219             beg, end = m.span()
    220             s = s[:beg] + s[beg + 1:end - 1] + s[end:]
    221             pos = m.end() - 2
    222         if pos >= len(s):
    223             words.append(s)
    224             break
    225 
    226     return words
    227 
    228 
    229 def execute(func, args, msg = None, verbose = 0, dry_run = 0):
    230     if msg is None:
    231         msg = '%s%r' % (func.__name__, args)
    232         if msg[-2:] == ',)':
    233             msg = msg[0:-2] + ')'
    234     log.info(msg)
    235     if not dry_run:
    236         func(*args)
    237 
    238 
    239 def strtobool(val):
    240     val = string.lower(val)
    241     if val in ('y', 'yes', 't', 'true', 'on', '1'):
    242         return 1
    243     if val in ('n', 'no', 'f', 'false', 'off', '0'):
    244         return 0
    245     raise ValueError, 'invalid truth value %r' % (val,)
    246 
    247 
    248 def byte_compile(py_files, optimize = 0, force = 0, prefix = None, base_dir = None, verbose = 1, dry_run = 0, direct = None):
    249     if sys.dont_write_bytecode:
    250         raise DistutilsByteCompileError('byte-compiling is disabled.')
    251     if direct is None:
    252         direct = __debug__ and optimize == 0
    253     if not direct:
    254         try:
    255             from tempfile import mkstemp
    256             script_fd, script_name = mkstemp('.py')
    257         except ImportError:
    258             from tempfile import mktemp
    259             script_fd, script_name = None, mktemp('.py')
    260 
    261         log.info("writing byte-compilation script '%s'", script_name)
    262         if not dry_run:
    263             if script_fd is not None:
    264                 script = os.fdopen(script_fd, 'w')
    265             else:
    266                 script = open(script_name, 'w')
    267             script.write('from distutils.util import byte_compile\nfiles = [\n')
    268             script.write(string.join(map(repr, py_files), ',\n') + ']\n')
    269             script.write('\nbyte_compile(files, optimize=%r, force=%r,\n             prefix=%r, base_dir=%r,\n             verbose=%r, dry_run=0,\n             direct=1)\n' % (optimize,
    270              force,
    271              prefix,
    272              base_dir,
    273              verbose))
    274             script.close()
    275         cmd = [sys.executable, script_name]
    276         if optimize == 1:
    277             cmd.insert(1, '-O')
    278         elif optimize == 2:
    279             cmd.insert(1, '-OO')
    280         spawn(cmd, dry_run=dry_run)
    281         execute(os.remove, (script_name,), 'removing %s' % script_name, dry_run=dry_run)
    282     else:
    283         from py_compile import compile
    284         for file in py_files:
    285             if file[-3:] != '.py':
    286                 continue
    287             cfile = file + (__debug__ and 'c' or 'o')
    288             dfile = file
    289             if prefix:
    290                 if file[:len(prefix)] != prefix:
    291                     raise ValueError, "invalid prefix: filename %r doesn't start with %r" % (file, prefix)
    292                 dfile = dfile[len(prefix):]
    293             if base_dir:
    294                 dfile = os.path.join(base_dir, dfile)
    295             cfile_base = os.path.basename(cfile)
    296             if direct:
    297                 if force or newer(file, cfile):
    298                     log.info('byte-compiling %s to %s', file, cfile_base)
    299                     if not dry_run:
    300                         compile(file, cfile, dfile)
    301                 else:
    302                     log.debug('skipping byte-compilation of %s to %s', file, cfile_base)
    303 
    304 
    305 def rfc822_escape(header):
    306     lines = string.split(header, '\n')
    307     header = string.join(lines, '\n' + '        ')
    308     return header