Permalink
Browse files

restore My Documents fallback for get_home_dir on Windows

  • Loading branch information...
1 parent db42b5f commit 9df2cbb93151a3694e1210cc6bbcc06212515fef @minrk committed Nov 23, 2011
Showing with 48 additions and 1 deletion.
  1. +16 −1 IPython/utils/path.py
  2. +32 −0 IPython/utils/tests/test_path.py
View
@@ -201,10 +201,25 @@ def get_home_dir(require_writable=False):
return py3compat.cast_unicode(root, fs_encoding)
homedir = os.path.expanduser('~')
+
+ if not _writable_dir(homedir) and os.name == 'nt':
+ # expanduser failed, use the registry to get the 'My Documents' folder.
+ try:
+ import _winreg as wreg
+ key = wreg.OpenKey(
+ wreg.HKEY_CURRENT_USER,
+ "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
+ )
+ homedir = wreg.QueryValueEx(key,'Personal')[0]
+ key.Close()
+ except:
+ pass
+
if (not require_writable) or _writable_dir(homedir):
return py3compat.cast_unicode(homedir, fs_encoding)
else:
- raise HomeDirError('%s is not a writable dir, set $HOME env to override' % homedir)
+ raise HomeDirError('%s is not a writable dir, '
+ 'set $HOME environment variable to override' % homedir)
def get_xdg_dir():
"""Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
@@ -166,8 +166,40 @@ def test_get_home_dir_4():
def test_get_home_dir_5():
"""raise HomeDirError if $HOME is specified, but not a writable dir"""
env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
+ # set os.name = posix, to prevent My Documents fallback on Windows
+ os.name = 'posix'
nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
+
+# Should we stub wreg fully so we can run the test on all platforms?
+@skip_if_not_win32
+@with_environment
+def test_get_home_dir_8():
+ """Using registry hack for 'My Documents', os=='nt'
+
+ HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
+ """
+ os.name = 'nt'
+ # Remove from stub environment all keys that may be set
+ for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
+ env.pop(key, None)
+
+ #Stub windows registry functions
+ def OpenKey(x, y):
+ class key:
+ def Close(self):
+ pass
+ return key()
+ def QueryValueEx(x, y):
+ return [abspath(HOME_TEST_DIR)]
+
+ wreg.OpenKey = OpenKey
+ wreg.QueryValueEx = QueryValueEx
+
+ home_dir = path.get_home_dir()
+ nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
+
+
@with_environment
def test_get_ipython_dir_1():
"""test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""

0 comments on commit 9df2cbb

Please sign in to comment.