home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / distutils / util.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  15.8 KB  |  470 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """distutils.util
  5.  
  6. Miscellaneous utility functions -- anything that doesn't fit into
  7. one of the other *util.py modules.
  8. """
  9. __revision__ = '$Id: util.py 74807 2009-09-15 19:14:37Z ronald.oussoren $'
  10. import sys
  11. import os
  12. import string
  13. import re
  14. from distutils.errors import DistutilsPlatformError
  15. from distutils.dep_util import newer
  16. from distutils.spawn import spawn
  17. from distutils import log
  18.  
  19. def get_platform():
  20.     """Return a string that identifies the current platform.  This is used
  21.     mainly to distinguish platform-specific build directories and
  22.     platform-specific built distributions.  Typically includes the OS name
  23.     and version and the architecture (as supplied by 'os.uname()'),
  24.     although the exact information included depends on the OS; eg. for IRIX
  25.     the architecture isn't particularly important (IRIX only runs on SGI
  26.     hardware), but for Linux the kernel version isn't particularly
  27.     important.
  28.  
  29.     Examples of returned values:
  30.        linux-i586
  31.        linux-alpha (?)
  32.        solaris-2.6-sun4u
  33.        irix-5.3
  34.        irix64-6.2
  35.  
  36.     Windows will return one of:
  37.        win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  38.        win-ia64 (64bit Windows on Itanium)
  39.        win32 (all others - specifically, sys.platform is returned)
  40.  
  41.     For other non-POSIX platforms, currently just returns 'sys.platform'.
  42.     """
  43.     if os.name == 'nt':
  44.         prefix = ' bit ('
  45.         i = string.find(sys.version, prefix)
  46.         if i == -1:
  47.             return sys.platform
  48.         j = string.find(sys.version, ')', i)
  49.         look = sys.version[i + len(prefix):j].lower()
  50.         if look == 'amd64':
  51.             return 'win-amd64'
  52.         if look == 'itanium':
  53.             return 'win-ia64'
  54.         return sys.platform
  55.     if os.name != 'posix' or not hasattr(os, 'uname'):
  56.         return sys.platform
  57.     (osname, host, release, version, machine) = os.uname()
  58.     osname = string.lower(osname)
  59.     osname = string.replace(osname, '/', '')
  60.     machine = string.replace(machine, ' ', '_')
  61.     machine = string.replace(machine, '/', '-')
  62.     if osname[:5] == 'linux':
  63.         return '%s-%s' % (osname, machine)
  64.     if osname[:5] == 'sunos':
  65.         if release[0] >= '5':
  66.             osname = 'solaris'
  67.             release = '%d.%s' % (int(release[0]) - 3, release[2:])
  68.         
  69.     elif osname[:4] == 'irix':
  70.         return '%s-%s' % (osname, release)
  71.     not hasattr(os, 'uname')
  72.     if osname[:3] == 'aix':
  73.         return '%s-%s.%s' % (osname, version, release)
  74.     if osname[:6] == 'cygwin':
  75.         osname = 'cygwin'
  76.         rel_re = re.compile('[\\d.]+')
  77.         m = rel_re.match(release)
  78.         if m:
  79.             release = m.group()
  80.         
  81.     elif osname[:6] == 'darwin':
  82.         get_config_vars = get_config_vars
  83.         import distutils.sysconfig
  84.         cfgvars = get_config_vars()
  85.         macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
  86.         if not macver:
  87.             macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
  88.         
  89.         macrelease = macver
  90.         
  91.         try:
  92.             f = open('/System/Library/CoreServices/SystemVersion.plist')
  93.         except IOError:
  94.             pass
  95.  
  96.         m = re.search('<key>ProductUserVisibleVersion</key>\\s*' + '<string>(.*?)</string>', f.read())
  97.         f.close()
  98.         if m is not None:
  99.             macrelease = '.'.join(m.group(1).split('.')[:2])
  100.         
  101.         if not macver:
  102.             macver = macrelease
  103.         
  104.         if macver:
  105.             get_config_vars = get_config_vars
  106.             import distutils.sysconfig
  107.             release = macver
  108.             osname = 'macosx'
  109.             if macrelease + '.' >= '10.4.' and '-arch' in get_config_vars().get('CFLAGS', '').strip():
  110.                 machine = 'fat'
  111.                 cflags = get_config_vars().get('CFLAGS')
  112.                 archs = re.findall('-arch\\s+(\\S+)', cflags)
  113.                 archs.sort()
  114.                 archs = tuple(archs)
  115.                 if len(archs) == 1:
  116.                     machine = archs[0]
  117.                 elif archs == ('i386', 'ppc'):
  118.                     machine = 'fat'
  119.                 elif archs == ('i386', 'x86_64'):
  120.                     machine = 'intel'
  121.                 elif archs == ('i386', 'ppc', 'x86_64'):
  122.                     machine = 'fat3'
  123.                 elif archs == ('ppc64', 'x86_64'):
  124.                     machine = 'fat64'
  125.                 elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
  126.                     machine = 'universal'
  127.                 else:
  128.                     raise ValueError("Don't know machine value for archs=%r" % (archs,))
  129.             len(archs) == 1
  130.             if machine in ('PowerPC', 'Power_Macintosh'):
  131.                 machine = 'ppc'
  132.             
  133.         
  134.     
  135.     return '%s-%s-%s' % (osname, release, machine)
  136.  
  137.  
  138. def convert_path(pathname):
  139.     """Return 'pathname' as a name that will work on the native filesystem,
  140.     i.e. split it on '/' and put it back together again using the current
  141.     directory separator.  Needed because filenames in the setup script are
  142.     always supplied in Unix style, and have to be converted to the local
  143.     convention before we can actually use them in the filesystem.  Raises
  144.     ValueError on non-Unix-ish systems if 'pathname' either starts or
  145.     ends with a slash.
  146.     """
  147.     if os.sep == '/':
  148.         return pathname
  149.     if not pathname:
  150.         return pathname
  151.     if pathname[0] == '/':
  152.         raise ValueError, "path '%s' cannot be absolute" % pathname
  153.     pathname[0] == '/'
  154.     if pathname[-1] == '/':
  155.         raise ValueError, "path '%s' cannot end with '/'" % pathname
  156.     pathname[-1] == '/'
  157.     paths = string.split(pathname, '/')
  158.     while '.' in paths:
  159.         paths.remove('.')
  160.         continue
  161.         pathname
  162.     if not paths:
  163.         return os.curdir
  164.     return apply(os.path.join, paths)
  165.  
  166.  
  167. def change_root(new_root, pathname):
  168.     '''Return \'pathname\' with \'new_root\' prepended.  If \'pathname\' is
  169.     relative, this is equivalent to "os.path.join(new_root,pathname)".
  170.     Otherwise, it requires making \'pathname\' relative and then joining the
  171.     two, which is tricky on DOS/Windows and Mac OS.
  172.     '''
  173.     if os.name == 'posix':
  174.         if not os.path.isabs(pathname):
  175.             return os.path.join(new_root, pathname)
  176.         return os.path.join(new_root, pathname[1:])
  177.     os.name == 'posix'
  178.     if os.name == 'nt':
  179.         (drive, path) = os.path.splitdrive(pathname)
  180.         if path[0] == '\\':
  181.             path = path[1:]
  182.         
  183.         return os.path.join(new_root, path)
  184.     if os.name == 'os2':
  185.         (drive, path) = os.path.splitdrive(pathname)
  186.         if path[0] == os.sep:
  187.             path = path[1:]
  188.         
  189.         return os.path.join(new_root, path)
  190.     if os.name == 'mac':
  191.         if not os.path.isabs(pathname):
  192.             return os.path.join(new_root, pathname)
  193.         elements = string.split(pathname, ':', 1)
  194.         pathname = ':' + elements[1]
  195.         return os.path.join(new_root, pathname)
  196.     os.name == 'mac'
  197.     raise DistutilsPlatformError, "nothing known about platform '%s'" % os.name
  198.  
  199. _environ_checked = 0
  200.  
  201. def check_environ():
  202.     """Ensure that 'os.environ' has all the environment variables we
  203.     guarantee that users can use in config files, command-line options,
  204.     etc.  Currently this includes:
  205.       HOME - user's home directory (Unix only)
  206.       PLAT - description of the current platform, including hardware
  207.              and OS (see 'get_platform()')
  208.     """
  209.     global _environ_checked
  210.     if _environ_checked:
  211.         return None
  212.     if os.name == 'posix' and 'HOME' not in os.environ:
  213.         import pwd
  214.         os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  215.     
  216.     if 'PLAT' not in os.environ:
  217.         os.environ['PLAT'] = get_platform()
  218.     
  219.     _environ_checked = 1
  220.  
  221.  
  222. def subst_vars(s, local_vars):
  223.     """Perform shell/Perl-style variable substitution on 'string'.  Every
  224.     occurrence of '$' followed by a name is considered a variable, and
  225.     variable is substituted by the value found in the 'local_vars'
  226.     dictionary, or in 'os.environ' if it's not in 'local_vars'.
  227.     'os.environ' is first checked/augmented to guarantee that it contains
  228.     certain values: see 'check_environ()'.  Raise ValueError for any
  229.     variables not found in either 'local_vars' or 'os.environ'.
  230.     """
  231.     check_environ()
  232.     
  233.     def _subst(match, local_vars = local_vars):
  234.         var_name = match.group(1)
  235.         if var_name in local_vars:
  236.             return str(local_vars[var_name])
  237.         return os.environ[var_name]
  238.  
  239.     
  240.     try:
  241.         return re.sub('\\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  242.     except KeyError:
  243.         var = None
  244.         raise ValueError, "invalid variable '$%s'" % var
  245.  
  246.  
  247.  
  248. def grok_environment_error(exc, prefix = 'error: '):
  249.     """Generate a useful error message from an EnvironmentError (IOError or
  250.     OSError) exception object.  Handles Python 1.5.1 and 1.5.2 styles, and
  251.     does what it can to deal with exception objects that don't have a
  252.     filename (which happens when the error is due to a two-file operation,
  253.     such as 'rename()' or 'link()'.  Returns the error message as a string
  254.     prefixed with 'prefix'.
  255.     """
  256.     if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
  257.         if exc.filename:
  258.             error = prefix + '%s: %s' % (exc.filename, exc.strerror)
  259.         else:
  260.             error = prefix + '%s' % exc.strerror
  261.     else:
  262.         error = prefix + str(exc[-1])
  263.     return error
  264.  
  265. _wordchars_re = None
  266. _squote_re = None
  267. _dquote_re = None
  268.  
  269. def _init_regex():
  270.     global _wordchars_re, _squote_re, _dquote_re
  271.     _wordchars_re = re.compile('[^\\\\\\\'\\"%s ]*' % string.whitespace)
  272.     _squote_re = re.compile("'(?:[^'\\\\]|\\\\.)*'")
  273.     _dquote_re = re.compile('"(?:[^"\\\\]|\\\\.)*"')
  274.  
  275.  
  276. def split_quoted(s):
  277.     '''Split a string up according to Unix shell-like rules for quotes and
  278.     backslashes.  In short: words are delimited by spaces, as long as those
  279.     spaces are not escaped by a backslash, or inside a quoted string.
  280.     Single and double quotes are equivalent, and the quote characters can
  281.     be backslash-escaped.  The backslash is stripped from any two-character
  282.     escape sequence, leaving only the escaped character.  The quote
  283.     characters are stripped from any quoted string.  Returns a list of
  284.     words.
  285.     '''
  286.     if _wordchars_re is None:
  287.         _init_regex()
  288.     
  289.     s = string.strip(s)
  290.     words = []
  291.     pos = 0
  292.     while s:
  293.         m = _wordchars_re.match(s, pos)
  294.         end = m.end()
  295.         if end == len(s):
  296.             words.append(s[:end])
  297.             break
  298.         
  299.         if s[end] in string.whitespace:
  300.             words.append(s[:end])
  301.             s = string.lstrip(s[end:])
  302.             pos = 0
  303.         elif s[end] == '\\':
  304.             s = s[:end] + s[end + 1:]
  305.             pos = end + 1
  306.         elif s[end] == "'":
  307.             m = _squote_re.match(s, end)
  308.         elif s[end] == '"':
  309.             m = _dquote_re.match(s, end)
  310.         else:
  311.             raise RuntimeError, "this can't happen (bad char '%c')" % s[end]
  312.         if s[end] in string.whitespace is None:
  313.             raise ValueError, 'bad string (mismatched %s quotes?)' % s[end]
  314.         s[end] in string.whitespace is None
  315.         (beg, end) = m.span()
  316.         s = s[:beg] + s[beg + 1:end - 1] + s[end:]
  317.         pos = m.end() - 2
  318.         if pos >= len(s):
  319.             words.append(s)
  320.             break
  321.             continue
  322.     return words
  323.  
  324.  
  325. def execute(func, args, msg = None, verbose = 0, dry_run = 0):
  326.     '''Perform some action that affects the outside world (eg.  by
  327.     writing to the filesystem).  Such actions are special because they
  328.     are disabled by the \'dry_run\' flag.  This method takes care of all
  329.     that bureaucracy for you; all you have to do is supply the
  330.     function to call and an argument tuple for it (to embody the
  331.     "external action" being performed), and an optional message to
  332.     print.
  333.     '''
  334.     if msg is None:
  335.         msg = '%s%r' % (func.__name__, args)
  336.         if msg[-2:] == ',)':
  337.             msg = msg[0:-2] + ')'
  338.         
  339.     
  340.     log.info(msg)
  341.     if not dry_run:
  342.         apply(func, args)
  343.     
  344.  
  345.  
  346. def strtobool(val):
  347.     """Convert a string representation of truth to true (1) or false (0).
  348.  
  349.     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  350.     are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
  351.     'val' is anything else.
  352.     """
  353.     val = string.lower(val)
  354.     if val in ('y', 'yes', 't', 'true', 'on', '1'):
  355.         return 1
  356.     if val in ('n', 'no', 'f', 'false', 'off', '0'):
  357.         return 0
  358.     raise ValueError, 'invalid truth value %r' % (val,)
  359.  
  360.  
  361. def byte_compile(py_files, optimize = 0, force = 0, prefix = None, base_dir = None, verbose = 1, dry_run = 0, direct = None):
  362.     '''Byte-compile a collection of Python source files to either .pyc
  363.     or .pyo files in the same directory.  \'py_files\' is a list of files
  364.     to compile; any files that don\'t end in ".py" are silently skipped.
  365.     \'optimize\' must be one of the following:
  366.       0 - don\'t optimize (generate .pyc)
  367.       1 - normal optimization (like "python -O")
  368.       2 - extra optimization (like "python -OO")
  369.     If \'force\' is true, all files are recompiled regardless of
  370.     timestamps.
  371.  
  372.     The source filename encoded in each bytecode file defaults to the
  373.     filenames listed in \'py_files\'; you can modify these with \'prefix\' and
  374.     \'basedir\'.  \'prefix\' is a string that will be stripped off of each
  375.     source filename, and \'base_dir\' is a directory name that will be
  376.     prepended (after \'prefix\' is stripped).  You can supply either or both
  377.     (or neither) of \'prefix\' and \'base_dir\', as you wish.
  378.  
  379.     If \'dry_run\' is true, doesn\'t actually do anything that would
  380.     affect the filesystem.
  381.  
  382.     Byte-compilation is either done directly in this interpreter process
  383.     with the standard py_compile module, or indirectly by writing a
  384.     temporary script and executing it.  Normally, you should let
  385.     \'byte_compile()\' figure out to use direct compilation or not (see
  386.     the source for details).  The \'direct\' flag is used by the script
  387.     generated in indirect mode; unless you know what you\'re doing, leave
  388.     it set to None.
  389.     '''
  390.     if direct is None:
  391.         if __debug__:
  392.             pass
  393.         direct = optimize == 0
  394.     
  395.     if not direct:
  396.         
  397.         try:
  398.             mkstemp = mkstemp
  399.             import tempfile
  400.             (script_fd, script_name) = mkstemp('.py')
  401.         except ImportError:
  402.             mktemp = mktemp
  403.             import tempfile
  404.             script_fd = None
  405.             script_name = mktemp('.py')
  406.  
  407.         log.info("writing byte-compilation script '%s'", script_name)
  408.         if not dry_run:
  409.             if script_fd is not None:
  410.                 script = os.fdopen(script_fd, 'w')
  411.             else:
  412.                 script = open(script_name, 'w')
  413.             script.write('from distutils.util import byte_compile\nfiles = [\n')
  414.             script.write(string.join(map(repr, py_files), ',\n') + ']\n')
  415.             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, force, prefix, base_dir, verbose))
  416.             script.close()
  417.         
  418.         cmd = [
  419.             sys.executable,
  420.             script_name]
  421.         if optimize == 1:
  422.             cmd.insert(1, '-O')
  423.         elif optimize == 2:
  424.             cmd.insert(1, '-OO')
  425.         
  426.         spawn(cmd, dry_run = dry_run)
  427.         execute(os.remove, (script_name,), 'removing %s' % script_name, dry_run = dry_run)
  428.     else:
  429.         compile = compile
  430.         import py_compile
  431.         for file in py_files:
  432.             if file[-3:] != '.py':
  433.                 continue
  434.             
  435.             if not __debug__ or 'c':
  436.                 pass
  437.             cfile = file + 'o'
  438.             dfile = file
  439.             if prefix:
  440.                 if file[:len(prefix)] != prefix:
  441.                     raise ValueError, "invalid prefix: filename %r doesn't start with %r" % (file, prefix)
  442.                 file[:len(prefix)] != prefix
  443.                 dfile = dfile[len(prefix):]
  444.             
  445.             if base_dir:
  446.                 dfile = os.path.join(base_dir, dfile)
  447.             
  448.             cfile_base = os.path.basename(cfile)
  449.             if direct:
  450.                 if force or newer(file, cfile):
  451.                     log.info('byte-compiling %s to %s', file, cfile_base)
  452.                     if not dry_run:
  453.                         compile(file, cfile, dfile)
  454.                     
  455.                 else:
  456.                     log.debug('skipping byte-compilation of %s to %s', file, cfile_base)
  457.             newer(file, cfile)
  458.         
  459.  
  460.  
  461. def rfc822_escape(header):
  462.     '''Return a version of the string escaped for inclusion in an
  463.     RFC-822 header, by ensuring there are 8 spaces space after each newline.
  464.     '''
  465.     lines = string.split(header, '\n')
  466.     lines = map(string.strip, lines)
  467.     header = string.join(lines, '\n' + '        ')
  468.     return header
  469.  
  470.