blob: 279f246726a769e23faeb1e8a96b943b27eac7d8 [file] [log] [blame]
Greg Ward2689e3d1999-03-22 14:52:19 +00001"""distutils.util
2
Greg Wardaebf7062000-04-04 02:05:59 +00003Miscellaneous utility functions -- anything that doesn't fit into
4one of the other *util.py modules."""
Greg Ward2689e3d1999-03-22 14:52:19 +00005
6# created 1999/03/08, Greg Ward
7
Greg Ward3ce77fd2000-03-02 01:49:45 +00008__revision__ = "$Id$"
Greg Ward2689e3d1999-03-22 14:52:19 +00009
Greg Warda7540bd2000-03-23 04:39:16 +000010import sys, os, string, re, shutil
Greg Ward2689e3d1999-03-22 14:52:19 +000011from distutils.errors import *
Greg Ward7c1a6d42000-03-29 02:48:40 +000012from distutils.spawn import spawn
Greg Ward2689e3d1999-03-22 14:52:19 +000013
Greg Wardaebf7062000-04-04 02:05:59 +000014# for backwards compatibility:
15from distutils.file_util import *
16from distutils.dir_util import *
17from distutils.dep_util import *
18from distutils.archive_util import *
Greg Ward585df892000-03-01 14:40:15 +000019
20
Greg Wardaa458bc2000-04-22 15:14:58 +000021# Need to define 'abspath()', because it was new with Python 1.5.2
22if hasattr (os.path, 'abspath'):
23 abspath = os.path.abspath
24else:
25 def abspath(path):
26 if not os.path.isabs(path):
27 path = os.path.join(os.getcwd(), path)
28 return os.path.normpath(path)
29
30
31# More backwards compatability hacks
32def extend (list, new_list):
33 """Appends the list 'new_list' to 'list', just like the 'extend()'
34 list method does in Python 1.5.2 -- but this works on earlier
35 versions of Python too."""
36
37 if hasattr (list, 'extend'):
38 list.extend (new_list)
39 else:
40 list[len(list):] = new_list
41
42# extend ()
43
44
Greg Ward585df892000-03-01 14:40:15 +000045def get_platform ():
46 """Return a string (suitable for tacking onto directory names) that
47 identifies the current platform. Under Unix, identifies both the OS
48 and hardware architecture, e.g. "linux-i586", "solaris-sparc",
49 "irix-mips". For Windows and Mac OS, just returns 'sys.platform' --
50 i.e. "???" or "???"."""
51
52 if os.name == 'posix':
Greg Ward6ce00b42000-03-31 04:40:25 +000053 (OS, _, rel, _, arch) = os.uname()
54 return "%s%c-%s" % (string.lower (OS), rel[0], string.lower (arch))
Greg Ward585df892000-03-01 14:40:15 +000055 else:
56 return sys.platform
57
58# get_platform()
Greg Ward50919292000-03-07 03:27:08 +000059
60
Greg Wardd8dfb4c2000-05-31 02:32:10 +000061def convert_path (pathname):
Greg Ward50919292000-03-07 03:27:08 +000062 """Return 'pathname' as a name that will work on the native
63 filesystem, i.e. split it on '/' and put it back together again
64 using the current directory separator. Needed because filenames in
65 the setup script are always supplied in Unix style, and have to be
66 converted to the local convention before we can actually use them in
Greg Ward02a1a2b2000-04-15 22:15:07 +000067 the filesystem. Raises ValueError if 'pathname' is
Greg Ward50919292000-03-07 03:27:08 +000068 absolute (starts with '/') or contains local directory separators
69 (unless the local separator is '/', of course)."""
70
71 if pathname[0] == '/':
Greg Ward02a1a2b2000-04-15 22:15:07 +000072 raise ValueError, "path '%s' cannot be absolute" % pathname
Greg Ward50919292000-03-07 03:27:08 +000073 if pathname[-1] == '/':
Greg Ward02a1a2b2000-04-15 22:15:07 +000074 raise ValueError, "path '%s' cannot end with '/'" % pathname
Greg Ward464023f2000-04-25 01:33:11 +000075 if os.sep != '/':
Greg Wardd8dfb4c2000-05-31 02:32:10 +000076 paths = string.split (pathname, '/')
77 return apply (os.path.join, paths)
Greg Ward50919292000-03-07 03:27:08 +000078 else:
79 return pathname
80
Greg Wardd8dfb4c2000-05-31 02:32:10 +000081# convert_path ()
Greg Ward1b4ede52000-03-22 00:22:44 +000082
83
Greg Ward67f75d42000-04-27 01:53:46 +000084def change_root (new_root, pathname):
Greg Ward67f75d42000-04-27 01:53:46 +000085 """Return 'pathname' with 'new_root' prepended. If 'pathname' is
86 relative, this is equivalent to "os.path.join(new_root,pathname)".
87 Otherwise, it requires making 'pathname' relative and then joining the
Greg Ward4b46ef92000-05-31 02:14:32 +000088 two, which is tricky on DOS/Windows and Mac OS.
89 """
90 if os.name == 'posix':
91 if not os.path.isabs (pathname):
92 return os.path.join (new_root, pathname)
93 else:
94 return os.path.join (new_root, pathname[1:])
Greg Ward67f75d42000-04-27 01:53:46 +000095
96 elif os.name == 'nt':
Greg Ward67f75d42000-04-27 01:53:46 +000097 (drive, path) = os.path.splitdrive (pathname)
Greg Ward4b46ef92000-05-31 02:14:32 +000098 if path[0] == '\\':
99 path = path[1:]
100 return os.path.join (new_root, path)
Greg Ward67f75d42000-04-27 01:53:46 +0000101
102 elif os.name == 'mac':
103 raise RuntimeError, "no clue how to do this on Mac OS"
104
105 else:
106 raise DistutilsPlatformError, \
107 "nothing known about platform '%s'" % os.name
108
109
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000110_environ_checked = 0
111def check_environ ():
Greg Ward1b4ede52000-03-22 00:22:44 +0000112 """Ensure that 'os.environ' has all the environment variables we
113 guarantee that users can use in config files, command-line
114 options, etc. Currently this includes:
115 HOME - user's home directory (Unix only)
116 PLAT - desription of the current platform, including hardware
117 and OS (see 'get_platform()')
118 """
119
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000120 global _environ_checked
121 if _environ_checked:
122 return
123
Greg Ward1b4ede52000-03-22 00:22:44 +0000124 if os.name == 'posix' and not os.environ.has_key('HOME'):
125 import pwd
126 os.environ['HOME'] = pwd.getpwuid (os.getuid())[5]
127
128 if not os.environ.has_key('PLAT'):
129 os.environ['PLAT'] = get_platform ()
130
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000131 _environ_checked = 1
132
Greg Ward1b4ede52000-03-22 00:22:44 +0000133
134def subst_vars (str, local_vars):
135 """Perform shell/Perl-style variable substitution on 'string'.
136 Every occurence of '$' followed by a name, or a name enclosed in
137 braces, is considered a variable. Every variable is substituted by
138 the value found in the 'local_vars' dictionary, or in 'os.environ'
139 if it's not in 'local_vars'. 'os.environ' is first checked/
140 augmented to guarantee that it contains certain values: see
141 '_check_environ()'. Raise ValueError for any variables not found in
142 either 'local_vars' or 'os.environ'."""
143
Gregory P. Smithe7e35ac2000-05-12 00:40:00 +0000144 check_environ ()
Greg Ward1b4ede52000-03-22 00:22:44 +0000145 def _subst (match, local_vars=local_vars):
146 var_name = match.group(1)
147 if local_vars.has_key (var_name):
148 return str (local_vars[var_name])
149 else:
150 return os.environ[var_name]
151
152 return re.sub (r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, str)
153
154# subst_vars ()
Greg Ward7c1a6d42000-03-29 02:48:40 +0000155
156
Greg Warde9055132000-06-17 02:16:46 +0000157def grok_environment_error (exc, prefix="error: "):
158 """Generate a useful error message from an EnvironmentError (IOError or
159 OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and
160 does what it can to deal with exception objects that don't have a
161 filename (which happens when the error is due to a two-file operation,
162 such as 'rename()' or 'link()'. Returns the error message as a string
163 prefixed with 'prefix'.
164 """
165 # check for Python 1.5.2-style {IO,OS}Error exception objects
166 if hasattr (exc, 'filename') and hasattr (exc, 'strerror'):
167 if exc.filename:
168 error = prefix + "%s: %s" % (exc.filename, exc.strerror)
169 else:
170 # two-argument functions in posix module don't
171 # include the filename in the exception object!
172 error = prefix + "%s" % exc.strerror
173 else:
174 error = prefix + str(exc[-1])
175
176 return error