##// END OF EJS Templates
Merge branch 'tilde-expand-fix'...
MinRK -
Show More
@@ -1,423 +1,425 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for path handling.
3 Utilities for path handling.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19
19
20 import IPython
20 import IPython
21 from IPython.utils import warn
21 from IPython.utils import warn
22 from IPython.utils.process import system
22 from IPython.utils.process import system
23 from IPython.utils.importstring import import_item
23 from IPython.utils.importstring import import_item
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Code
26 # Code
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29 fs_encoding = sys.getfilesystemencoding()
29 fs_encoding = sys.getfilesystemencoding()
30
30
31 def _cast_unicode(s, enc=None):
31 def _cast_unicode(s, enc=None):
32 """Turn 8-bit strings into unicode."""
32 """Turn 8-bit strings into unicode."""
33 if isinstance(s, bytes):
33 if isinstance(s, bytes):
34 enc = enc or sys.getdefaultencoding()
34 enc = enc or sys.getdefaultencoding()
35 return s.decode(enc)
35 return s.decode(enc)
36 return s
36 return s
37
37
38
38
39 def _get_long_path_name(path):
39 def _get_long_path_name(path):
40 """Dummy no-op."""
40 """Dummy no-op."""
41 return path
41 return path
42
42
43 if sys.platform == 'win32':
43 if sys.platform == 'win32':
44 def _get_long_path_name(path):
44 def _get_long_path_name(path):
45 """Get a long path name (expand ~) on Windows using ctypes.
45 """Get a long path name (expand ~) on Windows using ctypes.
46
46
47 Examples
47 Examples
48 --------
48 --------
49
49
50 >>> get_long_path_name('c:\\docume~1')
50 >>> get_long_path_name('c:\\docume~1')
51 u'c:\\\\Documents and Settings'
51 u'c:\\\\Documents and Settings'
52
52
53 """
53 """
54 try:
54 try:
55 import ctypes
55 import ctypes
56 except ImportError:
56 except ImportError:
57 raise ImportError('you need to have ctypes installed for this to work')
57 raise ImportError('you need to have ctypes installed for this to work')
58 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
58 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
59 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
59 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
60 ctypes.c_uint ]
60 ctypes.c_uint ]
61
61
62 buf = ctypes.create_unicode_buffer(260)
62 buf = ctypes.create_unicode_buffer(260)
63 rv = _GetLongPathName(path, buf, 260)
63 rv = _GetLongPathName(path, buf, 260)
64 if rv == 0 or rv > 260:
64 if rv == 0 or rv > 260:
65 return path
65 return path
66 else:
66 else:
67 return buf.value
67 return buf.value
68
68
69
69
70 def get_long_path_name(path):
70 def get_long_path_name(path):
71 """Expand a path into its long form.
71 """Expand a path into its long form.
72
72
73 On Windows this expands any ~ in the paths. On other platforms, it is
73 On Windows this expands any ~ in the paths. On other platforms, it is
74 a null operation.
74 a null operation.
75 """
75 """
76 return _get_long_path_name(path)
76 return _get_long_path_name(path)
77
77
78
78
79 def get_py_filename(name):
79 def get_py_filename(name):
80 """Return a valid python filename in the current directory.
80 """Return a valid python filename in the current directory.
81
81
82 If the given name is not a file, it adds '.py' and searches again.
82 If the given name is not a file, it adds '.py' and searches again.
83 Raises IOError with an informative message if the file isn't found."""
83 Raises IOError with an informative message if the file isn't found."""
84
84
85 name = os.path.expanduser(name)
85 name = os.path.expanduser(name)
86 if not os.path.isfile(name) and not name.endswith('.py'):
86 if not os.path.isfile(name) and not name.endswith('.py'):
87 name += '.py'
87 name += '.py'
88 if os.path.isfile(name):
88 if os.path.isfile(name):
89 return name
89 return name
90 else:
90 else:
91 raise IOError,'File `%s` not found.' % name
91 raise IOError,'File `%s` not found.' % name
92
92
93
93
94 def filefind(filename, path_dirs=None):
94 def filefind(filename, path_dirs=None):
95 """Find a file by looking through a sequence of paths.
95 """Find a file by looking through a sequence of paths.
96
96
97 This iterates through a sequence of paths looking for a file and returns
97 This iterates through a sequence of paths looking for a file and returns
98 the full, absolute path of the first occurence of the file. If no set of
98 the full, absolute path of the first occurence of the file. If no set of
99 path dirs is given, the filename is tested as is, after running through
99 path dirs is given, the filename is tested as is, after running through
100 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
100 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
101
101
102 filefind('myfile.txt')
102 filefind('myfile.txt')
103
103
104 will find the file in the current working dir, but::
104 will find the file in the current working dir, but::
105
105
106 filefind('~/myfile.txt')
106 filefind('~/myfile.txt')
107
107
108 Will find the file in the users home directory. This function does not
108 Will find the file in the users home directory. This function does not
109 automatically try any paths, such as the cwd or the user's home directory.
109 automatically try any paths, such as the cwd or the user's home directory.
110
110
111 Parameters
111 Parameters
112 ----------
112 ----------
113 filename : str
113 filename : str
114 The filename to look for.
114 The filename to look for.
115 path_dirs : str, None or sequence of str
115 path_dirs : str, None or sequence of str
116 The sequence of paths to look for the file in. If None, the filename
116 The sequence of paths to look for the file in. If None, the filename
117 need to be absolute or be in the cwd. If a string, the string is
117 need to be absolute or be in the cwd. If a string, the string is
118 put into a sequence and the searched. If a sequence, walk through
118 put into a sequence and the searched. If a sequence, walk through
119 each element and join with ``filename``, calling :func:`expandvars`
119 each element and join with ``filename``, calling :func:`expandvars`
120 and :func:`expanduser` before testing for existence.
120 and :func:`expanduser` before testing for existence.
121
121
122 Returns
122 Returns
123 -------
123 -------
124 Raises :exc:`IOError` or returns absolute path to file.
124 Raises :exc:`IOError` or returns absolute path to file.
125 """
125 """
126
126
127 # If paths are quoted, abspath gets confused, strip them...
127 # If paths are quoted, abspath gets confused, strip them...
128 filename = filename.strip('"').strip("'")
128 filename = filename.strip('"').strip("'")
129 # If the input is an absolute path, just check it exists
129 # If the input is an absolute path, just check it exists
130 if os.path.isabs(filename) and os.path.isfile(filename):
130 if os.path.isabs(filename) and os.path.isfile(filename):
131 return filename
131 return filename
132
132
133 if path_dirs is None:
133 if path_dirs is None:
134 path_dirs = ("",)
134 path_dirs = ("",)
135 elif isinstance(path_dirs, basestring):
135 elif isinstance(path_dirs, basestring):
136 path_dirs = (path_dirs,)
136 path_dirs = (path_dirs,)
137
137
138 for path in path_dirs:
138 for path in path_dirs:
139 if path == '.': path = os.getcwd()
139 if path == '.': path = os.getcwd()
140 testname = expand_path(os.path.join(path, filename))
140 testname = expand_path(os.path.join(path, filename))
141 if os.path.isfile(testname):
141 if os.path.isfile(testname):
142 return os.path.abspath(testname)
142 return os.path.abspath(testname)
143
143
144 raise IOError("File %r does not exist in any of the search paths: %r" %
144 raise IOError("File %r does not exist in any of the search paths: %r" %
145 (filename, path_dirs) )
145 (filename, path_dirs) )
146
146
147
147
148 class HomeDirError(Exception):
148 class HomeDirError(Exception):
149 pass
149 pass
150
150
151
151
152 def get_home_dir():
152 def get_home_dir():
153 """Return the closest possible equivalent to a 'home' directory.
153 """Return the closest possible equivalent to a 'home' directory.
154
154
155 * On POSIX, we try $HOME.
155 * On POSIX, we try $HOME.
156 * On Windows we try:
156 * On Windows we try:
157 - %HOMESHARE%
157 - %HOMESHARE%
158 - %HOMEDRIVE\%HOMEPATH%
158 - %HOMEDRIVE\%HOMEPATH%
159 - %USERPROFILE%
159 - %USERPROFILE%
160 - Registry hack for My Documents
160 - Registry hack for My Documents
161 - %HOME%: rare, but some people with unix-like setups may have defined it
161 - %HOME%: rare, but some people with unix-like setups may have defined it
162 * On Dos C:\
162 * On Dos C:\
163
163
164 Currently only Posix and NT are implemented, a HomeDirError exception is
164 Currently only Posix and NT are implemented, a HomeDirError exception is
165 raised for all other OSes.
165 raised for all other OSes.
166 """
166 """
167
167
168 isdir = os.path.isdir
168 isdir = os.path.isdir
169 env = os.environ
169 env = os.environ
170
170
171 # first, check py2exe distribution root directory for _ipython.
171 # first, check py2exe distribution root directory for _ipython.
172 # This overrides all. Normally does not exist.
172 # This overrides all. Normally does not exist.
173
173
174 if hasattr(sys, "frozen"): #Is frozen by py2exe
174 if hasattr(sys, "frozen"): #Is frozen by py2exe
175 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
175 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
176 root, rest = IPython.__file__.lower().split('library.zip')
176 root, rest = IPython.__file__.lower().split('library.zip')
177 else:
177 else:
178 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
178 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
179 root=os.path.abspath(root).rstrip('\\')
179 root=os.path.abspath(root).rstrip('\\')
180 if isdir(os.path.join(root, '_ipython')):
180 if isdir(os.path.join(root, '_ipython')):
181 os.environ["IPYKITROOT"] = root
181 os.environ["IPYKITROOT"] = root
182 return _cast_unicode(root, fs_encoding)
182 return _cast_unicode(root, fs_encoding)
183
183
184 if os.name == 'posix':
184 if os.name == 'posix':
185 # Linux, Unix, AIX, OS X
185 # Linux, Unix, AIX, OS X
186 try:
186 try:
187 homedir = env['HOME']
187 homedir = env['HOME']
188 except KeyError:
188 except KeyError:
189 # Last-ditch attempt at finding a suitable $HOME, on systems where
189 # Last-ditch attempt at finding a suitable $HOME, on systems where
190 # it may not be defined in the environment but the system shell
190 # it may not be defined in the environment but the system shell
191 # still knows it - reported once as:
191 # still knows it - reported once as:
192 # https://github.com/ipython/ipython/issues/154
192 # https://github.com/ipython/ipython/issues/154
193 from subprocess import Popen, PIPE
193 from subprocess import Popen, PIPE
194 homedir = Popen('echo $HOME', shell=True,
194 homedir = Popen('echo $HOME', shell=True,
195 stdout=PIPE).communicate()[0].strip()
195 stdout=PIPE).communicate()[0].strip()
196 if homedir:
196 if homedir:
197 return _cast_unicode(homedir, fs_encoding)
197 return _cast_unicode(homedir, fs_encoding)
198 else:
198 else:
199 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
199 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
200 else:
200 else:
201 return _cast_unicode(homedir, fs_encoding)
201 return _cast_unicode(homedir, fs_encoding)
202 elif os.name == 'nt':
202 elif os.name == 'nt':
203 # Now for win9x, XP, Vista, 7?
203 # Now for win9x, XP, Vista, 7?
204 # For some strange reason all of these return 'nt' for os.name.
204 # For some strange reason all of these return 'nt' for os.name.
205 # First look for a network home directory. This will return the UNC
205 # First look for a network home directory. This will return the UNC
206 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
206 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
207 # is needed when running IPython on cluster where all paths have to
207 # is needed when running IPython on cluster where all paths have to
208 # be UNC.
208 # be UNC.
209 try:
209 try:
210 homedir = env['HOMESHARE']
210 homedir = env['HOMESHARE']
211 except KeyError:
211 except KeyError:
212 pass
212 pass
213 else:
213 else:
214 if isdir(homedir):
214 if isdir(homedir):
215 return _cast_unicode(homedir, fs_encoding)
215 return _cast_unicode(homedir, fs_encoding)
216
216
217 # Now look for a local home directory
217 # Now look for a local home directory
218 try:
218 try:
219 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
219 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
220 except KeyError:
220 except KeyError:
221 pass
221 pass
222 else:
222 else:
223 if isdir(homedir):
223 if isdir(homedir):
224 return _cast_unicode(homedir, fs_encoding)
224 return _cast_unicode(homedir, fs_encoding)
225
225
226 # Now the users profile directory
226 # Now the users profile directory
227 try:
227 try:
228 homedir = os.path.join(env['USERPROFILE'])
228 homedir = os.path.join(env['USERPROFILE'])
229 except KeyError:
229 except KeyError:
230 pass
230 pass
231 else:
231 else:
232 if isdir(homedir):
232 if isdir(homedir):
233 return _cast_unicode(homedir, fs_encoding)
233 return _cast_unicode(homedir, fs_encoding)
234
234
235 # Use the registry to get the 'My Documents' folder.
235 # Use the registry to get the 'My Documents' folder.
236 try:
236 try:
237 import _winreg as wreg
237 import _winreg as wreg
238 key = wreg.OpenKey(
238 key = wreg.OpenKey(
239 wreg.HKEY_CURRENT_USER,
239 wreg.HKEY_CURRENT_USER,
240 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
240 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
241 )
241 )
242 homedir = wreg.QueryValueEx(key,'Personal')[0]
242 homedir = wreg.QueryValueEx(key,'Personal')[0]
243 key.Close()
243 key.Close()
244 except:
244 except:
245 pass
245 pass
246 else:
246 else:
247 if isdir(homedir):
247 if isdir(homedir):
248 return _cast_unicode(homedir, fs_encoding)
248 return _cast_unicode(homedir, fs_encoding)
249
249
250 # A user with a lot of unix tools in win32 may have defined $HOME.
250 # A user with a lot of unix tools in win32 may have defined $HOME.
251 # Try this as a last ditch option.
251 # Try this as a last ditch option.
252 try:
252 try:
253 homedir = env['HOME']
253 homedir = env['HOME']
254 except KeyError:
254 except KeyError:
255 pass
255 pass
256 else:
256 else:
257 if isdir(homedir):
257 if isdir(homedir):
258 return _cast_unicode(homedir, fs_encoding)
258 return _cast_unicode(homedir, fs_encoding)
259
259
260 # If all else fails, raise HomeDirError
260 # If all else fails, raise HomeDirError
261 raise HomeDirError('No valid home directory could be found')
261 raise HomeDirError('No valid home directory could be found')
262 elif os.name == 'dos':
262 elif os.name == 'dos':
263 # Desperate, may do absurd things in classic MacOS. May work under DOS.
263 # Desperate, may do absurd things in classic MacOS. May work under DOS.
264 return u'C:\\'
264 return u'C:\\'
265 else:
265 else:
266 raise HomeDirError('No valid home directory could be found for your OS')
266 raise HomeDirError('No valid home directory could be found for your OS')
267
267
268 def get_xdg_dir():
268 def get_xdg_dir():
269 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
269 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
270
270
271 This is only for posix (Linux,Unix,OS X, etc) systems.
271 This is only for posix (Linux,Unix,OS X, etc) systems.
272 """
272 """
273
273
274 isdir = os.path.isdir
274 isdir = os.path.isdir
275 env = os.environ
275 env = os.environ
276
276
277 if os.name == 'posix':
277 if os.name == 'posix':
278 # Linux, Unix, AIX, OS X
278 # Linux, Unix, AIX, OS X
279 # use ~/.config if not set OR empty
279 # use ~/.config if not set OR empty
280 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
280 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
281 if xdg and isdir(xdg):
281 if xdg and isdir(xdg):
282 return _cast_unicode(xdg, fs_encoding)
282 return _cast_unicode(xdg, fs_encoding)
283
283
284 return None
284 return None
285
285
286
286
287 def get_ipython_dir():
287 def get_ipython_dir():
288 """Get the IPython directory for this platform and user.
288 """Get the IPython directory for this platform and user.
289
289
290 This uses the logic in `get_home_dir` to find the home directory
290 This uses the logic in `get_home_dir` to find the home directory
291 and the adds .ipython to the end of the path.
291 and the adds .ipython to the end of the path.
292 """
292 """
293
293
294 env = os.environ
294 env = os.environ
295 pjoin = os.path.join
295 pjoin = os.path.join
296 exists = os.path.exists
296 exists = os.path.exists
297
297
298 ipdir_def = '.ipython'
298 ipdir_def = '.ipython'
299 xdg_def = 'ipython'
299 xdg_def = 'ipython'
300
300
301 home_dir = get_home_dir()
301 home_dir = get_home_dir()
302 xdg_dir = get_xdg_dir()
302 xdg_dir = get_xdg_dir()
303 # import pdb; pdb.set_trace() # dbg
303 # import pdb; pdb.set_trace() # dbg
304 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
304 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
305 if ipdir is None:
305 if ipdir is None:
306 # not set explicitly, use XDG_CONFIG_HOME or HOME
306 # not set explicitly, use XDG_CONFIG_HOME or HOME
307 home_ipdir = pjoin(home_dir, ipdir_def)
307 home_ipdir = pjoin(home_dir, ipdir_def)
308 if xdg_dir:
308 if xdg_dir:
309 # use XDG, as long as the user isn't already
309 # use XDG, as long as the user isn't already
310 # using $HOME/.ipython and *not* XDG/ipython
310 # using $HOME/.ipython and *not* XDG/ipython
311
311
312 xdg_ipdir = pjoin(xdg_dir, xdg_def)
312 xdg_ipdir = pjoin(xdg_dir, xdg_def)
313
313
314 if exists(xdg_ipdir) or not exists(home_ipdir):
314 if exists(xdg_ipdir) or not exists(home_ipdir):
315 ipdir = xdg_ipdir
315 ipdir = xdg_ipdir
316
316
317 if ipdir is None:
317 if ipdir is None:
318 # not using XDG
318 # not using XDG
319 ipdir = home_ipdir
319 ipdir = home_ipdir
320
320
321 ipdir = os.path.normpath(os.path.expanduser(ipdir))
322
321 return _cast_unicode(ipdir, fs_encoding)
323 return _cast_unicode(ipdir, fs_encoding)
322
324
323
325
324 def get_ipython_package_dir():
326 def get_ipython_package_dir():
325 """Get the base directory where IPython itself is installed."""
327 """Get the base directory where IPython itself is installed."""
326 ipdir = os.path.dirname(IPython.__file__)
328 ipdir = os.path.dirname(IPython.__file__)
327 return _cast_unicode(ipdir, fs_encoding)
329 return _cast_unicode(ipdir, fs_encoding)
328
330
329
331
330 def get_ipython_module_path(module_str):
332 def get_ipython_module_path(module_str):
331 """Find the path to an IPython module in this version of IPython.
333 """Find the path to an IPython module in this version of IPython.
332
334
333 This will always find the version of the module that is in this importable
335 This will always find the version of the module that is in this importable
334 IPython package. This will always return the path to the ``.py``
336 IPython package. This will always return the path to the ``.py``
335 version of the module.
337 version of the module.
336 """
338 """
337 if module_str == 'IPython':
339 if module_str == 'IPython':
338 return os.path.join(get_ipython_package_dir(), '__init__.py')
340 return os.path.join(get_ipython_package_dir(), '__init__.py')
339 mod = import_item(module_str)
341 mod = import_item(module_str)
340 the_path = mod.__file__.replace('.pyc', '.py')
342 the_path = mod.__file__.replace('.pyc', '.py')
341 the_path = the_path.replace('.pyo', '.py')
343 the_path = the_path.replace('.pyo', '.py')
342 return _cast_unicode(the_path, fs_encoding)
344 return _cast_unicode(the_path, fs_encoding)
343
345
344
346
345 def expand_path(s):
347 def expand_path(s):
346 """Expand $VARS and ~names in a string, like a shell
348 """Expand $VARS and ~names in a string, like a shell
347
349
348 :Examples:
350 :Examples:
349
351
350 In [2]: os.environ['FOO']='test'
352 In [2]: os.environ['FOO']='test'
351
353
352 In [3]: expand_path('variable FOO is $FOO')
354 In [3]: expand_path('variable FOO is $FOO')
353 Out[3]: 'variable FOO is test'
355 Out[3]: 'variable FOO is test'
354 """
356 """
355 # This is a pretty subtle hack. When expand user is given a UNC path
357 # This is a pretty subtle hack. When expand user is given a UNC path
356 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
358 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
357 # the $ to get (\\server\share\%username%). I think it considered $
359 # the $ to get (\\server\share\%username%). I think it considered $
358 # alone an empty var. But, we need the $ to remains there (it indicates
360 # alone an empty var. But, we need the $ to remains there (it indicates
359 # a hidden share).
361 # a hidden share).
360 if os.name=='nt':
362 if os.name=='nt':
361 s = s.replace('$\\', 'IPYTHON_TEMP')
363 s = s.replace('$\\', 'IPYTHON_TEMP')
362 s = os.path.expandvars(os.path.expanduser(s))
364 s = os.path.expandvars(os.path.expanduser(s))
363 if os.name=='nt':
365 if os.name=='nt':
364 s = s.replace('IPYTHON_TEMP', '$\\')
366 s = s.replace('IPYTHON_TEMP', '$\\')
365 return s
367 return s
366
368
367
369
368 def target_outdated(target,deps):
370 def target_outdated(target,deps):
369 """Determine whether a target is out of date.
371 """Determine whether a target is out of date.
370
372
371 target_outdated(target,deps) -> 1/0
373 target_outdated(target,deps) -> 1/0
372
374
373 deps: list of filenames which MUST exist.
375 deps: list of filenames which MUST exist.
374 target: single filename which may or may not exist.
376 target: single filename which may or may not exist.
375
377
376 If target doesn't exist or is older than any file listed in deps, return
378 If target doesn't exist or is older than any file listed in deps, return
377 true, otherwise return false.
379 true, otherwise return false.
378 """
380 """
379 try:
381 try:
380 target_time = os.path.getmtime(target)
382 target_time = os.path.getmtime(target)
381 except os.error:
383 except os.error:
382 return 1
384 return 1
383 for dep in deps:
385 for dep in deps:
384 dep_time = os.path.getmtime(dep)
386 dep_time = os.path.getmtime(dep)
385 if dep_time > target_time:
387 if dep_time > target_time:
386 #print "For target",target,"Dep failed:",dep # dbg
388 #print "For target",target,"Dep failed:",dep # dbg
387 #print "times (dep,tar):",dep_time,target_time # dbg
389 #print "times (dep,tar):",dep_time,target_time # dbg
388 return 1
390 return 1
389 return 0
391 return 0
390
392
391
393
392 def target_update(target,deps,cmd):
394 def target_update(target,deps,cmd):
393 """Update a target with a given command given a list of dependencies.
395 """Update a target with a given command given a list of dependencies.
394
396
395 target_update(target,deps,cmd) -> runs cmd if target is outdated.
397 target_update(target,deps,cmd) -> runs cmd if target is outdated.
396
398
397 This is just a wrapper around target_outdated() which calls the given
399 This is just a wrapper around target_outdated() which calls the given
398 command if target is outdated."""
400 command if target is outdated."""
399
401
400 if target_outdated(target,deps):
402 if target_outdated(target,deps):
401 system(cmd)
403 system(cmd)
402
404
403 def check_for_old_config(ipython_dir=None):
405 def check_for_old_config(ipython_dir=None):
404 """Check for old config files, and present a warning if they exist.
406 """Check for old config files, and present a warning if they exist.
405
407
406 A link to the docs of the new config is included in the message.
408 A link to the docs of the new config is included in the message.
407
409
408 This should mitigate confusion with the transition to the new
410 This should mitigate confusion with the transition to the new
409 config system in 0.11.
411 config system in 0.11.
410 """
412 """
411 if ipython_dir is None:
413 if ipython_dir is None:
412 ipython_dir = get_ipython_dir()
414 ipython_dir = get_ipython_dir()
413
415
414 old_configs = ['ipy_user_conf.py', 'ipythonrc']
416 old_configs = ['ipy_user_conf.py', 'ipythonrc']
415 for cfg in old_configs:
417 for cfg in old_configs:
416 f = os.path.join(ipython_dir, cfg)
418 f = os.path.join(ipython_dir, cfg)
417 if os.path.exists(f):
419 if os.path.exists(f):
418 warn.warn("""Found old IPython config file %r.
420 warn.warn("""Found old IPython config file %r.
419 The IPython configuration system has changed as of 0.11, and this file will be ignored.
421 The IPython configuration system has changed as of 0.11, and this file will be ignored.
420 See http://ipython.github.com/ipython-doc/dev/config for details on the new config system.
422 See http://ipython.github.com/ipython-doc/dev/config for details on the new config system.
421 The current default config file is 'ipython_config.py', where you can suppress these
423 The current default config file is 'ipython_config.py', where you can suppress these
422 warnings with `Global.ignore_old_config = True`."""%f)
424 warnings with `Global.ignore_old_config = True`."""%f)
423
425
@@ -1,359 +1,369 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.path.py"""
2 """Tests for IPython.utils.path.py"""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008 The IPython Development Team
5 # Copyright (C) 2008 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import shutil
16 import shutil
17 import sys
17 import sys
18 import tempfile
18 import tempfile
19
19
20 from os.path import join, abspath, split
20 from os.path import join, abspath, split
21
21
22 import nose.tools as nt
22 import nose.tools as nt
23
23
24 from nose import with_setup
24 from nose import with_setup
25
25
26 import IPython
26 import IPython
27 from IPython.testing import decorators as dec
27 from IPython.testing import decorators as dec
28 from IPython.testing.decorators import skip_if_not_win32, skip_win32
28 from IPython.testing.decorators import skip_if_not_win32, skip_win32
29 from IPython.utils import path
29 from IPython.utils import path
30
30
31 # Platform-dependent imports
31 # Platform-dependent imports
32 try:
32 try:
33 import _winreg as wreg
33 import _winreg as wreg
34 except ImportError:
34 except ImportError:
35 #Fake _winreg module on none windows platforms
35 #Fake _winreg module on none windows platforms
36 import new
36 import new
37 sys.modules["_winreg"] = new.module("_winreg")
37 sys.modules["_winreg"] = new.module("_winreg")
38 import _winreg as wreg
38 import _winreg as wreg
39 #Add entries that needs to be stubbed by the testing code
39 #Add entries that needs to be stubbed by the testing code
40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals
43 # Globals
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 env = os.environ
45 env = os.environ
46 TEST_FILE_PATH = split(abspath(__file__))[0]
46 TEST_FILE_PATH = split(abspath(__file__))[0]
47 TMP_TEST_DIR = tempfile.mkdtemp()
47 TMP_TEST_DIR = tempfile.mkdtemp()
48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
49 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
49 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
50 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
50 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
51 #
51 #
52 # Setup/teardown functions/decorators
52 # Setup/teardown functions/decorators
53 #
53 #
54
54
55 def setup():
55 def setup():
56 """Setup testenvironment for the module:
56 """Setup testenvironment for the module:
57
57
58 - Adds dummy home dir tree
58 - Adds dummy home dir tree
59 """
59 """
60 # Do not mask exceptions here. In particular, catching WindowsError is a
60 # Do not mask exceptions here. In particular, catching WindowsError is a
61 # problem because that exception is only defined on Windows...
61 # problem because that exception is only defined on Windows...
62 os.makedirs(IP_TEST_DIR)
62 os.makedirs(IP_TEST_DIR)
63 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
63 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
64
64
65
65
66 def teardown():
66 def teardown():
67 """Teardown testenvironment for the module:
67 """Teardown testenvironment for the module:
68
68
69 - Remove dummy home dir tree
69 - Remove dummy home dir tree
70 """
70 """
71 # Note: we remove the parent test dir, which is the root of all test
71 # Note: we remove the parent test dir, which is the root of all test
72 # subdirs we may have created. Use shutil instead of os.removedirs, so
72 # subdirs we may have created. Use shutil instead of os.removedirs, so
73 # that non-empty directories are all recursively removed.
73 # that non-empty directories are all recursively removed.
74 shutil.rmtree(TMP_TEST_DIR)
74 shutil.rmtree(TMP_TEST_DIR)
75
75
76
76
77 def setup_environment():
77 def setup_environment():
78 """Setup testenvironment for some functions that are tested
78 """Setup testenvironment for some functions that are tested
79 in this module. In particular this functions stores attributes
79 in this module. In particular this functions stores attributes
80 and other things that we need to stub in some test functions.
80 and other things that we need to stub in some test functions.
81 This needs to be done on a function level and not module level because
81 This needs to be done on a function level and not module level because
82 each testfunction needs a pristine environment.
82 each testfunction needs a pristine environment.
83 """
83 """
84 global oldstuff, platformstuff
84 global oldstuff, platformstuff
85 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
85 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
86
86
87 if os.name == 'nt':
87 if os.name == 'nt':
88 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
88 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
89
89
90
90
91 def teardown_environment():
91 def teardown_environment():
92 """Restore things that were remebered by the setup_environment function
92 """Restore things that were remebered by the setup_environment function
93 """
93 """
94 (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff
94 (oldenv, os.name, path.get_home_dir, IPython.__file__,) = oldstuff
95
95
96 for key in env.keys():
96 for key in env.keys():
97 if key not in oldenv:
97 if key not in oldenv:
98 del env[key]
98 del env[key]
99 env.update(oldenv)
99 env.update(oldenv)
100 if hasattr(sys, 'frozen'):
100 if hasattr(sys, 'frozen'):
101 del sys.frozen
101 del sys.frozen
102 if os.name == 'nt':
102 if os.name == 'nt':
103 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
103 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
104
104
105 # Build decorator that uses the setup_environment/setup_environment
105 # Build decorator that uses the setup_environment/setup_environment
106 with_environment = with_setup(setup_environment, teardown_environment)
106 with_environment = with_setup(setup_environment, teardown_environment)
107
107
108
108
109 @skip_if_not_win32
109 @skip_if_not_win32
110 @with_environment
110 @with_environment
111 def test_get_home_dir_1():
111 def test_get_home_dir_1():
112 """Testcase for py2exe logic, un-compressed lib
112 """Testcase for py2exe logic, un-compressed lib
113 """
113 """
114 sys.frozen = True
114 sys.frozen = True
115
115
116 #fake filename for IPython.__init__
116 #fake filename for IPython.__init__
117 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
117 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
118
118
119 home_dir = path.get_home_dir()
119 home_dir = path.get_home_dir()
120 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
120 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
121
121
122
122
123 @skip_if_not_win32
123 @skip_if_not_win32
124 @with_environment
124 @with_environment
125 def test_get_home_dir_2():
125 def test_get_home_dir_2():
126 """Testcase for py2exe logic, compressed lib
126 """Testcase for py2exe logic, compressed lib
127 """
127 """
128 sys.frozen = True
128 sys.frozen = True
129 #fake filename for IPython.__init__
129 #fake filename for IPython.__init__
130 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
130 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
131
131
132 home_dir = path.get_home_dir()
132 home_dir = path.get_home_dir()
133 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
133 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
134
134
135
135
136 @with_environment
136 @with_environment
137 @skip_win32
137 @skip_win32
138 def test_get_home_dir_3():
138 def test_get_home_dir_3():
139 """Testcase $HOME is set, then use its value as home directory."""
139 """Testcase $HOME is set, then use its value as home directory."""
140 env["HOME"] = HOME_TEST_DIR
140 env["HOME"] = HOME_TEST_DIR
141 home_dir = path.get_home_dir()
141 home_dir = path.get_home_dir()
142 nt.assert_equal(home_dir, env["HOME"])
142 nt.assert_equal(home_dir, env["HOME"])
143
143
144
144
145 @with_environment
145 @with_environment
146 def test_get_home_dir_4():
146 def test_get_home_dir_4():
147 """Testcase $HOME is not set, os=='posix'.
147 """Testcase $HOME is not set, os=='posix'.
148 This should fail with HomeDirError"""
148 This should fail with HomeDirError"""
149
149
150 os.name = 'posix'
150 os.name = 'posix'
151 if 'HOME' in env: del env['HOME']
151 if 'HOME' in env: del env['HOME']
152 nt.assert_raises(path.HomeDirError, path.get_home_dir)
152 nt.assert_raises(path.HomeDirError, path.get_home_dir)
153
153
154
154
155 @skip_if_not_win32
155 @skip_if_not_win32
156 @with_environment
156 @with_environment
157 def test_get_home_dir_5():
157 def test_get_home_dir_5():
158 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
158 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
159
159
160 HOMESHARE is missing.
160 HOMESHARE is missing.
161 """
161 """
162
162
163 os.name = 'nt'
163 os.name = 'nt'
164 env.pop('HOMESHARE', None)
164 env.pop('HOMESHARE', None)
165 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
165 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
166 home_dir = path.get_home_dir()
166 home_dir = path.get_home_dir()
167 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
167 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
168
168
169
169
170 @skip_if_not_win32
170 @skip_if_not_win32
171 @with_environment
171 @with_environment
172 def test_get_home_dir_6():
172 def test_get_home_dir_6():
173 """Using USERPROFILE, os=='nt'.
173 """Using USERPROFILE, os=='nt'.
174
174
175 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
175 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
176 """
176 """
177
177
178 os.name = 'nt'
178 os.name = 'nt'
179 env.pop('HOMESHARE', None)
179 env.pop('HOMESHARE', None)
180 env.pop('HOMEDRIVE', None)
180 env.pop('HOMEDRIVE', None)
181 env.pop('HOMEPATH', None)
181 env.pop('HOMEPATH', None)
182 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
182 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
183 home_dir = path.get_home_dir()
183 home_dir = path.get_home_dir()
184 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
184 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
185
185
186
186
187 @skip_if_not_win32
187 @skip_if_not_win32
188 @with_environment
188 @with_environment
189 def test_get_home_dir_7():
189 def test_get_home_dir_7():
190 """Using HOMESHARE, os=='nt'."""
190 """Using HOMESHARE, os=='nt'."""
191
191
192 os.name = 'nt'
192 os.name = 'nt'
193 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
193 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
194 home_dir = path.get_home_dir()
194 home_dir = path.get_home_dir()
195 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
195 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
196
196
197
197
198 # Should we stub wreg fully so we can run the test on all platforms?
198 # Should we stub wreg fully so we can run the test on all platforms?
199 @skip_if_not_win32
199 @skip_if_not_win32
200 @with_environment
200 @with_environment
201 def test_get_home_dir_8():
201 def test_get_home_dir_8():
202 """Using registry hack for 'My Documents', os=='nt'
202 """Using registry hack for 'My Documents', os=='nt'
203
203
204 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
204 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
205 """
205 """
206 os.name = 'nt'
206 os.name = 'nt'
207 # Remove from stub environment all keys that may be set
207 # Remove from stub environment all keys that may be set
208 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
208 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
209 env.pop(key, None)
209 env.pop(key, None)
210
210
211 #Stub windows registry functions
211 #Stub windows registry functions
212 def OpenKey(x, y):
212 def OpenKey(x, y):
213 class key:
213 class key:
214 def Close(self):
214 def Close(self):
215 pass
215 pass
216 return key()
216 return key()
217 def QueryValueEx(x, y):
217 def QueryValueEx(x, y):
218 return [abspath(HOME_TEST_DIR)]
218 return [abspath(HOME_TEST_DIR)]
219
219
220 wreg.OpenKey = OpenKey
220 wreg.OpenKey = OpenKey
221 wreg.QueryValueEx = QueryValueEx
221 wreg.QueryValueEx = QueryValueEx
222
222
223 home_dir = path.get_home_dir()
223 home_dir = path.get_home_dir()
224 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
224 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
225
225
226
226
227 @with_environment
227 @with_environment
228 def test_get_ipython_dir_1():
228 def test_get_ipython_dir_1():
229 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
229 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
230 env['IPYTHON_DIR'] = "someplace/.ipython"
230 env['IPYTHON_DIR'] = "someplace/.ipython"
231 ipdir = path.get_ipython_dir()
231 ipdir = path.get_ipython_dir()
232 nt.assert_equal(ipdir, "someplace/.ipython")
232 nt.assert_equal(ipdir, "someplace/.ipython")
233
233
234
234
235 @with_environment
235 @with_environment
236 def test_get_ipython_dir_2():
236 def test_get_ipython_dir_2():
237 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
237 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
238 path.get_home_dir = lambda : "someplace"
238 path.get_home_dir = lambda : "someplace"
239 os.name = "posix"
239 os.name = "posix"
240 env.pop('IPYTHON_DIR', None)
240 env.pop('IPYTHON_DIR', None)
241 env.pop('IPYTHONDIR', None)
241 env.pop('IPYTHONDIR', None)
242 env.pop('XDG_CONFIG_HOME', None)
242 env.pop('XDG_CONFIG_HOME', None)
243 ipdir = path.get_ipython_dir()
243 ipdir = path.get_ipython_dir()
244 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
244 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
245
245
246 @with_environment
246 @with_environment
247 def test_get_ipython_dir_3():
247 def test_get_ipython_dir_3():
248 """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist."""
248 """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist."""
249 path.get_home_dir = lambda : "someplace"
249 path.get_home_dir = lambda : "someplace"
250 os.name = "posix"
250 os.name = "posix"
251 env.pop('IPYTHON_DIR', None)
251 env.pop('IPYTHON_DIR', None)
252 env.pop('IPYTHONDIR', None)
252 env.pop('IPYTHONDIR', None)
253 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
253 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
254 ipdir = path.get_ipython_dir()
254 ipdir = path.get_ipython_dir()
255 nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython"))
255 nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython"))
256
256
257 @with_environment
257 @with_environment
258 def test_get_ipython_dir_4():
258 def test_get_ipython_dir_4():
259 """test_get_ipython_dir_4, use XDG if both exist."""
259 """test_get_ipython_dir_4, use XDG if both exist."""
260 path.get_home_dir = lambda : HOME_TEST_DIR
260 path.get_home_dir = lambda : HOME_TEST_DIR
261 os.name = "posix"
261 os.name = "posix"
262 env.pop('IPYTHON_DIR', None)
262 env.pop('IPYTHON_DIR', None)
263 env.pop('IPYTHONDIR', None)
263 env.pop('IPYTHONDIR', None)
264 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
264 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
265 xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython")
265 xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython")
266 ipdir = path.get_ipython_dir()
266 ipdir = path.get_ipython_dir()
267 nt.assert_equal(ipdir, xdg_ipdir)
267 nt.assert_equal(ipdir, xdg_ipdir)
268
268
269 @with_environment
269 @with_environment
270 def test_get_ipython_dir_5():
270 def test_get_ipython_dir_5():
271 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
271 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
272 path.get_home_dir = lambda : HOME_TEST_DIR
272 os.name = "posix"
273 os.name = "posix"
273 env.pop('IPYTHON_DIR', None)
274 env.pop('IPYTHON_DIR', None)
274 env.pop('IPYTHONDIR', None)
275 env.pop('IPYTHONDIR', None)
275 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
276 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
276 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
277 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
277 ipdir = path.get_ipython_dir()
278 ipdir = path.get_ipython_dir()
278 nt.assert_equal(ipdir, IP_TEST_DIR)
279 nt.assert_equal(ipdir, IP_TEST_DIR)
279
280
280 @with_environment
281 @with_environment
281 def test_get_ipython_dir_6():
282 def test_get_ipython_dir_6():
282 """test_get_ipython_dir_6, use XDG if defined and neither exist."""
283 """test_get_ipython_dir_6, use XDG if defined and neither exist."""
283 path.get_home_dir = lambda : 'somehome'
284 path.get_home_dir = lambda : 'somehome'
284 path.get_xdg_dir = lambda : 'somexdg'
285 path.get_xdg_dir = lambda : 'somexdg'
285 os.name = "posix"
286 os.name = "posix"
286 env.pop('IPYTHON_DIR', None)
287 env.pop('IPYTHON_DIR', None)
287 env.pop('IPYTHONDIR', None)
288 env.pop('IPYTHONDIR', None)
288 xdg_ipdir = os.path.join("somexdg", "ipython")
289 xdg_ipdir = os.path.join("somexdg", "ipython")
289 ipdir = path.get_ipython_dir()
290 ipdir = path.get_ipython_dir()
290 nt.assert_equal(ipdir, xdg_ipdir)
291 nt.assert_equal(ipdir, xdg_ipdir)
291
292
292 @with_environment
293 @with_environment
294 def test_get_ipython_dir_7():
295 """test_get_ipython_dir_7, test home directory expansion on IPYTHON_DIR"""
296 home_dir = os.path.expanduser('~/')
297 env['IPYTHON_DIR'] = '~/somewhere'
298 ipdir = path.get_ipython_dir()
299 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
300
301
302 @with_environment
293 def test_get_xdg_dir_1():
303 def test_get_xdg_dir_1():
294 """test_get_xdg_dir_1, check xdg_dir"""
304 """test_get_xdg_dir_1, check xdg_dir"""
295 reload(path)
305 reload(path)
296 path.get_home_dir = lambda : 'somewhere'
306 path.get_home_dir = lambda : 'somewhere'
297 os.name = "posix"
307 os.name = "posix"
298 env.pop('IPYTHON_DIR', None)
308 env.pop('IPYTHON_DIR', None)
299 env.pop('IPYTHONDIR', None)
309 env.pop('IPYTHONDIR', None)
300 env.pop('XDG_CONFIG_HOME', None)
310 env.pop('XDG_CONFIG_HOME', None)
301
311
302 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
312 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
303
313
304
314
305 @with_environment
315 @with_environment
306 def test_get_xdg_dir_1():
316 def test_get_xdg_dir_1():
307 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
317 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
308 reload(path)
318 reload(path)
309 path.get_home_dir = lambda : HOME_TEST_DIR
319 path.get_home_dir = lambda : HOME_TEST_DIR
310 os.name = "posix"
320 os.name = "posix"
311 env.pop('IPYTHON_DIR', None)
321 env.pop('IPYTHON_DIR', None)
312 env.pop('IPYTHONDIR', None)
322 env.pop('IPYTHONDIR', None)
313 env.pop('XDG_CONFIG_HOME', None)
323 env.pop('XDG_CONFIG_HOME', None)
314 nt.assert_equal(path.get_xdg_dir(), None)
324 nt.assert_equal(path.get_xdg_dir(), None)
315
325
316 @with_environment
326 @with_environment
317 def test_get_xdg_dir_2():
327 def test_get_xdg_dir_2():
318 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
328 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
319 reload(path)
329 reload(path)
320 path.get_home_dir = lambda : HOME_TEST_DIR
330 path.get_home_dir = lambda : HOME_TEST_DIR
321 os.name = "posix"
331 os.name = "posix"
322 env.pop('IPYTHON_DIR', None)
332 env.pop('IPYTHON_DIR', None)
323 env.pop('IPYTHONDIR', None)
333 env.pop('IPYTHONDIR', None)
324 env.pop('XDG_CONFIG_HOME', None)
334 env.pop('XDG_CONFIG_HOME', None)
325 cfgdir=os.path.join(path.get_home_dir(), '.config')
335 cfgdir=os.path.join(path.get_home_dir(), '.config')
326 os.makedirs(cfgdir)
336 os.makedirs(cfgdir)
327
337
328 nt.assert_equal(path.get_xdg_dir(), cfgdir)
338 nt.assert_equal(path.get_xdg_dir(), cfgdir)
329
339
330 def test_filefind():
340 def test_filefind():
331 """Various tests for filefind"""
341 """Various tests for filefind"""
332 f = tempfile.NamedTemporaryFile()
342 f = tempfile.NamedTemporaryFile()
333 # print 'fname:',f.name
343 # print 'fname:',f.name
334 alt_dirs = path.get_ipython_dir()
344 alt_dirs = path.get_ipython_dir()
335 t = path.filefind(f.name, alt_dirs)
345 t = path.filefind(f.name, alt_dirs)
336 # print 'found:',t
346 # print 'found:',t
337
347
338
348
339 def test_get_ipython_package_dir():
349 def test_get_ipython_package_dir():
340 ipdir = path.get_ipython_package_dir()
350 ipdir = path.get_ipython_package_dir()
341 nt.assert_true(os.path.isdir(ipdir))
351 nt.assert_true(os.path.isdir(ipdir))
342
352
343
353
344 def test_get_ipython_module_path():
354 def test_get_ipython_module_path():
345 ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp')
355 ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp')
346 nt.assert_true(os.path.isfile(ipapp_path))
356 nt.assert_true(os.path.isfile(ipapp_path))
347
357
348
358
349 @dec.skip_if_not_win32
359 @dec.skip_if_not_win32
350 def test_get_long_path_name_win32():
360 def test_get_long_path_name_win32():
351 p = path.get_long_path_name('c:\\docume~1')
361 p = path.get_long_path_name('c:\\docume~1')
352 nt.assert_equals(p,u'c:\\Documents and Settings')
362 nt.assert_equals(p,u'c:\\Documents and Settings')
353
363
354
364
355 @dec.skip_win32
365 @dec.skip_win32
356 def test_get_long_path_name():
366 def test_get_long_path_name():
357 p = path.get_long_path_name('/usr/local')
367 p = path.get_long_path_name('/usr/local')
358 nt.assert_equals(p,'/usr/local')
368 nt.assert_equals(p,'/usr/local')
359
369
General Comments 0
You need to be logged in to leave comments. Login now