##// END OF EJS Templates
Merge pull request #8214 from takluyver/split-utils-path...
Min RK -
r21066:a6fd3b1a merge
parent child Browse files
Show More
@@ -0,0 +1,246 b''
1 from contextlib import contextmanager
2 import errno
3 import os
4 import shutil
5 import sys
6 import tempfile
7 import warnings
8
9 try:
10 reload
11 except NameError: # Python 3
12 from imp import reload
13
14 from nose import with_setup
15 import nose.tools as nt
16
17 import IPython
18 from IPython import paths
19 from IPython.testing.decorators import skip_win32
20 from IPython.utils.tempdir import TemporaryDirectory
21
22 env = os.environ
23 TMP_TEST_DIR = tempfile.mkdtemp()
24 HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir")
25 XDG_TEST_DIR = os.path.join(HOME_TEST_DIR, "xdg_test_dir")
26 XDG_CACHE_DIR = os.path.join(HOME_TEST_DIR, "xdg_cache_dir")
27 IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython')
28
29 def setup():
30 """Setup testenvironment for the module:
31
32 - Adds dummy home dir tree
33 """
34 # Do not mask exceptions here. In particular, catching WindowsError is a
35 # problem because that exception is only defined on Windows...
36 os.makedirs(IP_TEST_DIR)
37 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
38 os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython'))
39
40
41 def teardown():
42 """Teardown testenvironment for the module:
43
44 - Remove dummy home dir tree
45 """
46 # Note: we remove the parent test dir, which is the root of all test
47 # subdirs we may have created. Use shutil instead of os.removedirs, so
48 # that non-empty directories are all recursively removed.
49 shutil.rmtree(TMP_TEST_DIR)
50
51
52 def setup_environment():
53 """Setup testenvironment for some functions that are tested
54 in this module. In particular this functions stores attributes
55 and other things that we need to stub in some test functions.
56 This needs to be done on a function level and not module level because
57 each testfunction needs a pristine environment.
58 """
59 global oldstuff, platformstuff
60 oldstuff = (env.copy(), os.name, sys.platform, paths.get_home_dir, IPython.__file__, os.getcwd())
61
62 def teardown_environment():
63 """Restore things that were remembered by the setup_environment function
64 """
65 (oldenv, os.name, sys.platform, paths.get_home_dir, IPython.__file__, old_wd) = oldstuff
66 os.chdir(old_wd)
67 reload(paths)
68
69 for key in list(env):
70 if key not in oldenv:
71 del env[key]
72 env.update(oldenv)
73 if hasattr(sys, 'frozen'):
74 del sys.frozen
75
76 # Build decorator that uses the setup_environment/setup_environment
77 with_environment = with_setup(setup_environment, teardown_environment)
78
79 @contextmanager
80 def patch_get_home_dir(dirpath):
81 orig_get_home_dir = paths.get_home_dir
82 paths.get_home_dir = lambda : dirpath
83 try:
84 yield
85 finally:
86 paths.get_home_dir = orig_get_home_dir
87
88
89 @with_environment
90 def test_get_ipython_dir_1():
91 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
92 env_ipdir = os.path.join("someplace", ".ipython")
93 paths._writable_dir = lambda path: True
94 env['IPYTHONDIR'] = env_ipdir
95 ipdir = paths.get_ipython_dir()
96 nt.assert_equal(ipdir, env_ipdir)
97
98
99 @with_environment
100 def test_get_ipython_dir_2():
101 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
102 with patch_get_home_dir('someplace'):
103 paths.get_xdg_dir = lambda : None
104 paths._writable_dir = lambda path: True
105 os.name = "posix"
106 env.pop('IPYTHON_DIR', None)
107 env.pop('IPYTHONDIR', None)
108 env.pop('XDG_CONFIG_HOME', None)
109 ipdir = paths.get_ipython_dir()
110 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
111
112 @with_environment
113 def test_get_ipython_dir_3():
114 """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
115 tmphome = TemporaryDirectory()
116 try:
117 with patch_get_home_dir(tmphome.name):
118 os.name = "posix"
119 env.pop('IPYTHON_DIR', None)
120 env.pop('IPYTHONDIR', None)
121 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
122
123 with warnings.catch_warnings(record=True) as w:
124 ipdir = paths.get_ipython_dir()
125
126 nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
127 if sys.platform != 'darwin':
128 nt.assert_equal(len(w), 1)
129 nt.assert_in('Moving', str(w[0]))
130 finally:
131 tmphome.cleanup()
132
133 @with_environment
134 def test_get_ipython_dir_4():
135 """test_get_ipython_dir_4, warn if XDG and home both exist."""
136 with patch_get_home_dir(HOME_TEST_DIR):
137 os.name = "posix"
138 env.pop('IPYTHON_DIR', None)
139 env.pop('IPYTHONDIR', None)
140 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
141 try:
142 os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython'))
143 except OSError as e:
144 if e.errno != errno.EEXIST:
145 raise
146
147 with warnings.catch_warnings(record=True) as w:
148 ipdir = paths.get_ipython_dir()
149
150 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython"))
151 if sys.platform != 'darwin':
152 nt.assert_equal(len(w), 1)
153 nt.assert_in('Ignoring', str(w[0]))
154
155 @with_environment
156 def test_get_ipython_dir_5():
157 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
158 with patch_get_home_dir(HOME_TEST_DIR):
159 os.name = "posix"
160 env.pop('IPYTHON_DIR', None)
161 env.pop('IPYTHONDIR', None)
162 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
163 try:
164 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
165 except OSError as e:
166 if e.errno != errno.ENOENT:
167 raise
168 ipdir = paths.get_ipython_dir()
169 nt.assert_equal(ipdir, IP_TEST_DIR)
170
171 @with_environment
172 def test_get_ipython_dir_6():
173 """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
174 xdg = os.path.join(HOME_TEST_DIR, 'somexdg')
175 os.mkdir(xdg)
176 shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython'))
177 with patch_get_home_dir(HOME_TEST_DIR):
178 orig_get_xdg_dir = paths.get_xdg_dir
179 paths.get_xdg_dir = lambda : xdg
180 try:
181 os.name = "posix"
182 env.pop('IPYTHON_DIR', None)
183 env.pop('IPYTHONDIR', None)
184 env.pop('XDG_CONFIG_HOME', None)
185 with warnings.catch_warnings(record=True) as w:
186 ipdir = paths.get_ipython_dir()
187
188 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython'))
189 nt.assert_equal(len(w), 0)
190 finally:
191 paths.get_xdg_dir = orig_get_xdg_dir
192
193 @with_environment
194 def test_get_ipython_dir_7():
195 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
196 paths._writable_dir = lambda path: True
197 home_dir = os.path.normpath(os.path.expanduser('~'))
198 env['IPYTHONDIR'] = os.path.join('~', 'somewhere')
199 ipdir = paths.get_ipython_dir()
200 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
201
202 @skip_win32
203 @with_environment
204 def test_get_ipython_dir_8():
205 """test_get_ipython_dir_8, test / home directory"""
206 old = paths._writable_dir, paths.get_xdg_dir
207 try:
208 paths._writable_dir = lambda path: bool(path)
209 paths.get_xdg_dir = lambda: None
210 env.pop('IPYTHON_DIR', None)
211 env.pop('IPYTHONDIR', None)
212 env['HOME'] = '/'
213 nt.assert_equal(paths.get_ipython_dir(), '/.ipython')
214 finally:
215 paths._writable_dir, paths.get_xdg_dir = old
216
217
218 @with_environment
219 def test_get_ipython_cache_dir():
220 os.environ["HOME"] = HOME_TEST_DIR
221 if os.name == 'posix' and sys.platform != 'darwin':
222 # test default
223 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
224 os.environ.pop("XDG_CACHE_HOME", None)
225 ipdir = paths.get_ipython_cache_dir()
226 nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
227 ipdir)
228 nt.assert_true(os.path.isdir(ipdir))
229
230 # test env override
231 os.environ["XDG_CACHE_HOME"] = XDG_CACHE_DIR
232 ipdir = paths.get_ipython_cache_dir()
233 nt.assert_true(os.path.isdir(ipdir))
234 nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
235 else:
236 nt.assert_equal(paths.get_ipython_cache_dir(),
237 paths.get_ipython_dir())
238
239 def test_get_ipython_package_dir():
240 ipdir = paths.get_ipython_package_dir()
241 nt.assert_true(os.path.isdir(ipdir))
242
243
244 def test_get_ipython_module_path():
245 ipapp_path = paths.get_ipython_module_path('IPython.terminal.ipapp')
246 nt.assert_true(os.path.isfile(ipapp_path))
@@ -0,0 +1,118 b''
1 import os.path
2 import shutil
3 import tempfile
4 from warnings import warn
5
6 import IPython
7 from IPython.utils.importstring import import_item
8 from IPython.utils.path import (
9 get_home_dir, get_xdg_dir, get_xdg_cache_dir, compress_user, _writable_dir,
10 ensure_dir_exists, fs_encoding, filefind
11 )
12 from IPython.utils import py3compat
13
14 def get_ipython_dir():
15 """Get the IPython directory for this platform and user.
16
17 This uses the logic in `get_home_dir` to find the home directory
18 and then adds .ipython to the end of the path.
19 """
20
21 env = os.environ
22 pjoin = os.path.join
23
24
25 ipdir_def = '.ipython'
26
27 home_dir = get_home_dir()
28 xdg_dir = get_xdg_dir()
29
30 # import pdb; pdb.set_trace() # dbg
31 if 'IPYTHON_DIR' in env:
32 warn('The environment variable IPYTHON_DIR is deprecated. '
33 'Please use IPYTHONDIR instead.')
34 ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
35 if ipdir is None:
36 # not set explicitly, use ~/.ipython
37 ipdir = pjoin(home_dir, ipdir_def)
38 if xdg_dir:
39 # Several IPython versions (up to 1.x) defaulted to .config/ipython
40 # on Linux. We have decided to go back to using .ipython everywhere
41 xdg_ipdir = pjoin(xdg_dir, 'ipython')
42
43 if _writable_dir(xdg_ipdir):
44 cu = compress_user
45 if os.path.exists(ipdir):
46 warn(('Ignoring {0} in favour of {1}. Remove {0} to '
47 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
48 elif os.path.islink(xdg_ipdir):
49 warn(('{0} is deprecated. Move link to {1} to '
50 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
51 else:
52 warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
53 shutil.move(xdg_ipdir, ipdir)
54
55 ipdir = os.path.normpath(os.path.expanduser(ipdir))
56
57 if os.path.exists(ipdir) and not _writable_dir(ipdir):
58 # ipdir exists, but is not writable
59 warn("IPython dir '{0}' is not a writable location,"
60 " using a temp directory.".format(ipdir))
61 ipdir = tempfile.mkdtemp()
62 elif not os.path.exists(ipdir):
63 parent = os.path.dirname(ipdir)
64 if not _writable_dir(parent):
65 # ipdir does not exist and parent isn't writable
66 warn("IPython parent '{0}' is not a writable location,"
67 " using a temp directory.".format(parent))
68 ipdir = tempfile.mkdtemp()
69
70 return py3compat.cast_unicode(ipdir, fs_encoding)
71
72
73 def get_ipython_cache_dir():
74 """Get the cache directory it is created if it does not exist."""
75 xdgdir = get_xdg_cache_dir()
76 if xdgdir is None:
77 return get_ipython_dir()
78 ipdir = os.path.join(xdgdir, "ipython")
79 if not os.path.exists(ipdir) and _writable_dir(xdgdir):
80 ensure_dir_exists(ipdir)
81 elif not _writable_dir(xdgdir):
82 return get_ipython_dir()
83
84 return py3compat.cast_unicode(ipdir, fs_encoding)
85
86
87 def get_ipython_package_dir():
88 """Get the base directory where IPython itself is installed."""
89 ipdir = os.path.dirname(IPython.__file__)
90 return py3compat.cast_unicode(ipdir, fs_encoding)
91
92
93 def get_ipython_module_path(module_str):
94 """Find the path to an IPython module in this version of IPython.
95
96 This will always find the version of the module that is in this importable
97 IPython package. This will always return the path to the ``.py``
98 version of the module.
99 """
100 if module_str == 'IPython':
101 return os.path.join(get_ipython_package_dir(), '__init__.py')
102 mod = import_item(module_str)
103 the_path = mod.__file__.replace('.pyc', '.py')
104 the_path = the_path.replace('.pyo', '.py')
105 return py3compat.cast_unicode(the_path, fs_encoding)
106
107 def locate_profile(profile='default'):
108 """Find the path to the folder associated with a given profile.
109
110 I.e. find $IPYTHONDIR/profile_whatever.
111 """
112 from IPython.core.profiledir import ProfileDir, ProfileDirError
113 try:
114 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
115 except ProfileDirError:
116 # IOError makes more sense when people are expecting a path
117 raise IOError("Couldn't find profile %r" % profile)
118 return pd.location
@@ -34,7 +34,7 b' from IPython.core.shellapp import ('
34 from IPython.extensions.storemagic import StoreMagics
34 from IPython.extensions.storemagic import StoreMagics
35 from IPython.terminal.interactiveshell import TerminalInteractiveShell
35 from IPython.terminal.interactiveshell import TerminalInteractiveShell
36 from IPython.utils import warn
36 from IPython.utils import warn
37 from IPython.utils.path import get_ipython_dir, check_for_old_config
37 from IPython.utils.path import get_ipython_dir
38 from IPython.utils.traitlets import (
38 from IPython.utils.traitlets import (
39 Bool, List, Dict,
39 Bool, List, Dict,
40 )
40 )
@@ -246,16 +246,12 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
246 # *do* autocreate requested profile, but don't create the config file.
246 # *do* autocreate requested profile, but don't create the config file.
247 auto_create=Bool(True)
247 auto_create=Bool(True)
248 # configurables
248 # configurables
249 ignore_old_config=Bool(False, config=True,
250 help="Suppress warning messages about legacy config files"
251 )
252 quick = Bool(False, config=True,
249 quick = Bool(False, config=True,
253 help="""Start IPython quickly by skipping the loading of config files."""
250 help="""Start IPython quickly by skipping the loading of config files."""
254 )
251 )
255 def _quick_changed(self, name, old, new):
252 def _quick_changed(self, name, old, new):
256 if new:
253 if new:
257 self.load_config_file = lambda *a, **kw: None
254 self.load_config_file = lambda *a, **kw: None
258 self.ignore_old_config=True
259
255
260 display_banner = Bool(True, config=True,
256 display_banner = Bool(True, config=True,
261 help="Whether to display a banner upon starting IPython."
257 help="Whether to display a banner upon starting IPython."
@@ -307,8 +303,6 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
307 if self.subapp is not None:
303 if self.subapp is not None:
308 # don't bother initializing further, starting subapp
304 # don't bother initializing further, starting subapp
309 return
305 return
310 if not self.ignore_old_config:
311 check_for_old_config(self.ipython_dir)
312 # print self.extra_args
306 # print self.extra_args
313 if self.extra_args and not self.something_to_run:
307 if self.extra_args and not self.something_to_run:
314 self.file_to_run = self.extra_args[0]
308 self.file_to_run = self.extra_args[0]
@@ -16,11 +16,11 b' import glob'
16 from warnings import warn
16 from warnings import warn
17 from hashlib import md5
17 from hashlib import md5
18
18
19 import IPython
20 from IPython.testing.skipdoctest import skip_doctest
19 from IPython.testing.skipdoctest import skip_doctest
21 from IPython.utils.process import system
20 from IPython.utils.process import system
22 from IPython.utils.importstring import import_item
23 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22 from IPython.utils.decorators import undoc
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
@@ -254,111 +254,35 b' def get_xdg_cache_dir():'
254 return None
254 return None
255
255
256
256
257 @undoc
257 def get_ipython_dir():
258 def get_ipython_dir():
258 """Get the IPython directory for this platform and user.
259 warn("get_ipython_dir has moved to the IPython.paths module")
259
260 from IPython.paths import get_ipython_dir
260 This uses the logic in `get_home_dir` to find the home directory
261 return get_ipython_dir()
261 and then adds .ipython to the end of the path.
262 """
263
264 env = os.environ
265 pjoin = os.path.join
266
267
268 ipdir_def = '.ipython'
269
270 home_dir = get_home_dir()
271 xdg_dir = get_xdg_dir()
272
273 # import pdb; pdb.set_trace() # dbg
274 if 'IPYTHON_DIR' in env:
275 warn('The environment variable IPYTHON_DIR is deprecated. '
276 'Please use IPYTHONDIR instead.')
277 ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
278 if ipdir is None:
279 # not set explicitly, use ~/.ipython
280 ipdir = pjoin(home_dir, ipdir_def)
281 if xdg_dir:
282 # Several IPython versions (up to 1.x) defaulted to .config/ipython
283 # on Linux. We have decided to go back to using .ipython everywhere
284 xdg_ipdir = pjoin(xdg_dir, 'ipython')
285
286 if _writable_dir(xdg_ipdir):
287 cu = compress_user
288 if os.path.exists(ipdir):
289 warn(('Ignoring {0} in favour of {1}. Remove {0} to '
290 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
291 elif os.path.islink(xdg_ipdir):
292 warn(('{0} is deprecated. Move link to {1} to '
293 'get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
294 else:
295 warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
296 shutil.move(xdg_ipdir, ipdir)
297
298 ipdir = os.path.normpath(os.path.expanduser(ipdir))
299
300 if os.path.exists(ipdir) and not _writable_dir(ipdir):
301 # ipdir exists, but is not writable
302 warn("IPython dir '{0}' is not a writable location,"
303 " using a temp directory.".format(ipdir))
304 ipdir = tempfile.mkdtemp()
305 elif not os.path.exists(ipdir):
306 parent = os.path.dirname(ipdir)
307 if not _writable_dir(parent):
308 # ipdir does not exist and parent isn't writable
309 warn("IPython parent '{0}' is not a writable location,"
310 " using a temp directory.".format(parent))
311 ipdir = tempfile.mkdtemp()
312
313 return py3compat.cast_unicode(ipdir, fs_encoding)
314
315
262
263 @undoc
316 def get_ipython_cache_dir():
264 def get_ipython_cache_dir():
317 """Get the cache directory it is created if it does not exist."""
265 warn("get_ipython_cache_dir has moved to the IPython.paths module")
318 xdgdir = get_xdg_cache_dir()
266 from IPython.paths import get_ipython_cache_dir
319 if xdgdir is None:
267 return get_ipython_cache_dir()
320 return get_ipython_dir()
321 ipdir = os.path.join(xdgdir, "ipython")
322 if not os.path.exists(ipdir) and _writable_dir(xdgdir):
323 ensure_dir_exists(ipdir)
324 elif not _writable_dir(xdgdir):
325 return get_ipython_dir()
326
327 return py3compat.cast_unicode(ipdir, fs_encoding)
328
329
268
269 @undoc
330 def get_ipython_package_dir():
270 def get_ipython_package_dir():
331 """Get the base directory where IPython itself is installed."""
271 warn("get_ipython_package_dir has moved to the IPython.paths module")
332 ipdir = os.path.dirname(IPython.__file__)
272 from IPython.paths import get_ipython_package_dir
333 return py3compat.cast_unicode(ipdir, fs_encoding)
273 return get_ipython_package_dir()
334
335
274
275 @undoc
336 def get_ipython_module_path(module_str):
276 def get_ipython_module_path(module_str):
337 """Find the path to an IPython module in this version of IPython.
277 warn("get_ipython_module_path has moved to the IPython.paths module")
338
278 from IPython.paths import get_ipython_module_path
339 This will always find the version of the module that is in this importable
279 return get_ipython_module_path(module_str)
340 IPython package. This will always return the path to the ``.py``
341 version of the module.
342 """
343 if module_str == 'IPython':
344 return os.path.join(get_ipython_package_dir(), '__init__.py')
345 mod = import_item(module_str)
346 the_path = mod.__file__.replace('.pyc', '.py')
347 the_path = the_path.replace('.pyo', '.py')
348 return py3compat.cast_unicode(the_path, fs_encoding)
349
280
281 @undoc
350 def locate_profile(profile='default'):
282 def locate_profile(profile='default'):
351 """Find the path to the folder associated with a given profile.
283 warn("locate_profile has moved to the IPython.paths module")
352
284 from IPython.paths import locate_profile
353 I.e. find $IPYTHONDIR/profile_whatever.
285 return locate_profile(profile=profile)
354 """
355 from IPython.core.profiledir import ProfileDir, ProfileDirError
356 try:
357 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
358 except ProfileDirError:
359 # IOError makes more sense when people are expecting a path
360 raise IOError("Couldn't find profile %r" % profile)
361 return pd.location
362
286
363 def expand_path(s):
287 def expand_path(s):
364 """Expand $VARS and ~names in a string, like a shell
288 """Expand $VARS and ~names in a string, like a shell
@@ -443,83 +367,14 b' def target_update(target,deps,cmd):'
443 if target_outdated(target,deps):
367 if target_outdated(target,deps):
444 system(cmd)
368 system(cmd)
445
369
370 @undoc
446 def filehash(path):
371 def filehash(path):
447 """Make an MD5 hash of a file, ignoring any differences in line
372 """Make an MD5 hash of a file, ignoring any differences in line
448 ending characters."""
373 ending characters."""
374 warn("filehash() is deprecated")
449 with open(path, "rU") as f:
375 with open(path, "rU") as f:
450 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
376 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
451
377
452 # If the config is unmodified from the default, we'll just delete it.
453 # These are consistent for 0.10.x, thankfully. We're not going to worry about
454 # older versions.
455 old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3',
456 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'}
457
458 def check_for_old_config(ipython_dir=None):
459 """Check for old config files, and present a warning if they exist.
460
461 A link to the docs of the new config is included in the message.
462
463 This should mitigate confusion with the transition to the new
464 config system in 0.11.
465 """
466 if ipython_dir is None:
467 ipython_dir = get_ipython_dir()
468
469 old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
470 warned = False
471 for cfg in old_configs:
472 f = os.path.join(ipython_dir, cfg)
473 if os.path.exists(f):
474 if filehash(f) == old_config_md5.get(cfg, ''):
475 os.unlink(f)
476 else:
477 warn("Found old IPython config file {!r} (modified by user)".format(f))
478 warned = True
479
480 if warned:
481 warn("""
482 The IPython configuration system has changed as of 0.11, and these files will
483 be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
484 of the new config system.
485 To start configuring IPython, do `ipython profile create`, and edit
486 `ipython_config.py` in <ipython_dir>/profile_default.
487 If you need to leave the old config files in place for an older version of
488 IPython and want to suppress this warning message, set
489 `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")
490
491 def get_security_file(filename, profile='default'):
492 """Return the absolute path of a security file given by filename and profile
493
494 This allows users and developers to find security files without
495 knowledge of the IPython directory structure. The search path
496 will be ['.', profile.security_dir]
497
498 Parameters
499 ----------
500
501 filename : str
502 The file to be found. If it is passed as an absolute path, it will
503 simply be returned.
504 profile : str [default: 'default']
505 The name of the profile to search. Leaving this unspecified
506 The file to be found. If it is passed as an absolute path, fname will
507 simply be returned.
508
509 Returns
510 -------
511 Raises :exc:`IOError` if file not found or returns absolute path to file.
512 """
513 # import here, because profiledir also imports from utils.path
514 from IPython.core.profiledir import ProfileDir
515 try:
516 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
517 except Exception:
518 # will raise ProfileDirError if no such profile
519 raise IOError("Profile %r not found")
520 return filefind(filename, ['.', pd.security_dir])
521
522
523 ENOLINK = 1998
378 ENOLINK = 1998
524
379
525 def link(src, dst):
380 def link(src, dst):
@@ -60,12 +60,8 b' except NameError: # Python 3'
60 # Globals
60 # Globals
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 env = os.environ
62 env = os.environ
63 TEST_FILE_PATH = split(abspath(__file__))[0]
64 TMP_TEST_DIR = tempfile.mkdtemp()
63 TMP_TEST_DIR = tempfile.mkdtemp()
65 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
64 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
66 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
67 XDG_CACHE_DIR = join(HOME_TEST_DIR, "xdg_cache_dir")
68 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
69 #
65 #
70 # Setup/teardown functions/decorators
66 # Setup/teardown functions/decorators
71 #
67 #
@@ -77,9 +73,7 b' def setup():'
77 """
73 """
78 # Do not mask exceptions here. In particular, catching WindowsError is a
74 # Do not mask exceptions here. In particular, catching WindowsError is a
79 # problem because that exception is only defined on Windows...
75 # problem because that exception is only defined on Windows...
80 os.makedirs(IP_TEST_DIR)
76 os.makedirs(os.path.join(HOME_TEST_DIR, 'ipython'))
81 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
82 os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython'))
83
77
84
78
85 def teardown():
79 def teardown():
@@ -120,15 +114,6 b' def teardown_environment():'
120 # Build decorator that uses the setup_environment/setup_environment
114 # Build decorator that uses the setup_environment/setup_environment
121 with_environment = with_setup(setup_environment, teardown_environment)
115 with_environment = with_setup(setup_environment, teardown_environment)
122
116
123 @contextmanager
124 def patch_get_home_dir(dirpath):
125 orig_get_home_dir = path.get_home_dir
126 path.get_home_dir = lambda : dirpath
127 try:
128 yield
129 finally:
130 path.get_home_dir = orig_get_home_dir
131
132 @skip_if_not_win32
117 @skip_if_not_win32
133 @with_environment
118 @with_environment
134 def test_get_home_dir_1():
119 def test_get_home_dir_1():
@@ -205,135 +190,6 b' def test_get_home_dir_8():'
205 home_dir = path.get_home_dir()
190 home_dir = path.get_home_dir()
206 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
191 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
207
192
208
209 @with_environment
210 def test_get_ipython_dir_1():
211 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
212 env_ipdir = os.path.join("someplace", ".ipython")
213 path._writable_dir = lambda path: True
214 env['IPYTHONDIR'] = env_ipdir
215 ipdir = path.get_ipython_dir()
216 nt.assert_equal(ipdir, env_ipdir)
217
218
219 @with_environment
220 def test_get_ipython_dir_2():
221 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
222 with patch_get_home_dir('someplace'):
223 path.get_xdg_dir = lambda : None
224 path._writable_dir = lambda path: True
225 os.name = "posix"
226 env.pop('IPYTHON_DIR', None)
227 env.pop('IPYTHONDIR', None)
228 env.pop('XDG_CONFIG_HOME', None)
229 ipdir = path.get_ipython_dir()
230 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
231
232 @with_environment
233 def test_get_ipython_dir_3():
234 """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
235 tmphome = TemporaryDirectory()
236 try:
237 with patch_get_home_dir(tmphome.name):
238 os.name = "posix"
239 env.pop('IPYTHON_DIR', None)
240 env.pop('IPYTHONDIR', None)
241 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
242
243 with warnings.catch_warnings(record=True) as w:
244 ipdir = path.get_ipython_dir()
245
246 nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
247 if sys.platform != 'darwin':
248 nt.assert_equal(len(w), 1)
249 nt.assert_in('Moving', str(w[0]))
250 finally:
251 tmphome.cleanup()
252
253 @with_environment
254 def test_get_ipython_dir_4():
255 """test_get_ipython_dir_4, warn if XDG and home both exist."""
256 with patch_get_home_dir(HOME_TEST_DIR):
257 os.name = "posix"
258 env.pop('IPYTHON_DIR', None)
259 env.pop('IPYTHONDIR', None)
260 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
261 try:
262 os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython'))
263 except OSError as e:
264 if e.errno != errno.EEXIST:
265 raise
266
267 with warnings.catch_warnings(record=True) as w:
268 ipdir = path.get_ipython_dir()
269
270 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython"))
271 if sys.platform != 'darwin':
272 nt.assert_equal(len(w), 1)
273 nt.assert_in('Ignoring', str(w[0]))
274
275 @with_environment
276 def test_get_ipython_dir_5():
277 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
278 with patch_get_home_dir(HOME_TEST_DIR):
279 os.name = "posix"
280 env.pop('IPYTHON_DIR', None)
281 env.pop('IPYTHONDIR', None)
282 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
283 try:
284 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
285 except OSError as e:
286 if e.errno != errno.ENOENT:
287 raise
288 ipdir = path.get_ipython_dir()
289 nt.assert_equal(ipdir, IP_TEST_DIR)
290
291 @with_environment
292 def test_get_ipython_dir_6():
293 """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
294 xdg = os.path.join(HOME_TEST_DIR, 'somexdg')
295 os.mkdir(xdg)
296 shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython'))
297 with patch_get_home_dir(HOME_TEST_DIR):
298 orig_get_xdg_dir = path.get_xdg_dir
299 path.get_xdg_dir = lambda : xdg
300 try:
301 os.name = "posix"
302 env.pop('IPYTHON_DIR', None)
303 env.pop('IPYTHONDIR', None)
304 env.pop('XDG_CONFIG_HOME', None)
305 with warnings.catch_warnings(record=True) as w:
306 ipdir = path.get_ipython_dir()
307
308 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython'))
309 nt.assert_equal(len(w), 0)
310 finally:
311 path.get_xdg_dir = orig_get_xdg_dir
312
313 @with_environment
314 def test_get_ipython_dir_7():
315 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
316 path._writable_dir = lambda path: True
317 home_dir = os.path.normpath(os.path.expanduser('~'))
318 env['IPYTHONDIR'] = os.path.join('~', 'somewhere')
319 ipdir = path.get_ipython_dir()
320 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
321
322 @skip_win32
323 @with_environment
324 def test_get_ipython_dir_8():
325 """test_get_ipython_dir_8, test / home directory"""
326 old = path._writable_dir, path.get_xdg_dir
327 try:
328 path._writable_dir = lambda path: bool(path)
329 path.get_xdg_dir = lambda: None
330 env.pop('IPYTHON_DIR', None)
331 env.pop('IPYTHONDIR', None)
332 env['HOME'] = '/'
333 nt.assert_equal(path.get_ipython_dir(), '/.ipython')
334 finally:
335 path._writable_dir, path.get_xdg_dir = old
336
337 @with_environment
193 @with_environment
338 def test_get_xdg_dir_0():
194 def test_get_xdg_dir_0():
339 """test_get_xdg_dir_0, check xdg_dir"""
195 """test_get_xdg_dir_0, check xdg_dir"""
@@ -401,36 +257,6 b' def test_filefind():'
401 t = path.filefind(f.name, alt_dirs)
257 t = path.filefind(f.name, alt_dirs)
402 # print 'found:',t
258 # print 'found:',t
403
259
404 @with_environment
405 def test_get_ipython_cache_dir():
406 os.environ["HOME"] = HOME_TEST_DIR
407 if os.name == 'posix' and sys.platform != 'darwin':
408 # test default
409 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
410 os.environ.pop("XDG_CACHE_HOME", None)
411 ipdir = path.get_ipython_cache_dir()
412 nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
413 ipdir)
414 nt.assert_true(os.path.isdir(ipdir))
415
416 # test env override
417 os.environ["XDG_CACHE_HOME"] = XDG_CACHE_DIR
418 ipdir = path.get_ipython_cache_dir()
419 nt.assert_true(os.path.isdir(ipdir))
420 nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
421 else:
422 nt.assert_equal(path.get_ipython_cache_dir(),
423 path.get_ipython_dir())
424
425 def test_get_ipython_package_dir():
426 ipdir = path.get_ipython_package_dir()
427 nt.assert_true(os.path.isdir(ipdir))
428
429
430 def test_get_ipython_module_path():
431 ipapp_path = path.get_ipython_module_path('IPython.terminal.ipapp')
432 nt.assert_true(os.path.isfile(ipapp_path))
433
434
260
435 @dec.skip_if_not_win32
261 @dec.skip_if_not_win32
436 def test_get_long_path_name_win32():
262 def test_get_long_path_name_win32():
@@ -20,7 +20,7 b' import zmq'
20
20
21 from IPython.kernel.zmq.session import Session
21 from IPython.kernel.zmq.session import Session
22 from IPython.utils.py3compat import str_to_bytes
22 from IPython.utils.py3compat import str_to_bytes
23 from IPython.utils.path import get_security_file
23 from jupyter_client.connect import find_connection_file
24
24
25 def main(connection_file):
25 def main(connection_file):
26 """watch iopub channel, and print messages"""
26 """watch iopub channel, and print messages"""
@@ -73,5 +73,5 b" if __name__ == '__main__':"
73 cf = sys.argv[1]
73 cf = sys.argv[1]
74 else:
74 else:
75 # This gets the security file for the default profile:
75 # This gets the security file for the default profile:
76 cf = get_security_file('ipcontroller-client.json')
76 cf = find_connection_file('ipcontroller-client.json')
77 main(cf)
77 main(cf)
General Comments 0
You need to be logged in to leave comments. Login now