From 9df2cbb93151a3694e1210cc6bbcc06212515fef 2011-11-23 05:00:31 From: MinRK Date: 2011-11-23 05:00:31 Subject: [PATCH] restore My Documents fallback for get_home_dir on Windows --- diff --git a/IPython/utils/path.py b/IPython/utils/path.py index cf59b9a..64b0f76 100644 --- a/IPython/utils/path.py +++ b/IPython/utils/path.py @@ -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. diff --git a/IPython/utils/tests/test_path.py b/IPython/utils/tests/test_path.py index 93aa4dc..1cc928c 100644 --- a/IPython/utils/tests/test_path.py +++ b/IPython/utils/tests/test_path.py @@ -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."""