@@ -68,21 +68,49 @@ def get_home_dir() -> str:
68
68
_dtemps : Dict [str , str ] = {}
69
69
70
70
71
+ def _do_i_own (path : str ) -> bool :
72
+ """Return whether the current user owns the given path"""
73
+ p = Path (path ).resolve ()
74
+
75
+ # walk up to first existing parent
76
+ while not p .exists () and p != p .parent :
77
+ p = p .parent
78
+
79
+ # simplest check: owner by name
80
+ # not always implemented or available
81
+ try :
82
+ return p .owner () == os .getlogin ()
83
+ except (NotImplementedError , OSError ):
84
+ pass
85
+
86
+ if hasattr (os , 'geteuid' ):
87
+ try :
88
+ st = p .stat ()
89
+ return st .st_uid == os .geteuid ()
90
+ except (NotImplementedError , OSError ):
91
+ # geteuid not always implemented
92
+ pass
93
+
94
+ # no ownership checks worked, check write access
95
+ return os .access (p , os .W_OK )
96
+
97
+
71
98
def prefer_environment_over_user () -> bool :
72
99
"""Determine if environment-level paths should take precedence over user-level paths."""
73
100
# If JUPYTER_PREFER_ENV_PATH is defined, that signals user intent, so return its value
74
101
if "JUPYTER_PREFER_ENV_PATH" in os .environ :
75
102
return envset ("JUPYTER_PREFER_ENV_PATH" ) # type:ignore[return-value]
76
103
77
104
# If we are in a Python virtualenv, default to True (see https://docs.python.org/3/library/venv.html#venv-def)
78
- if sys .prefix != sys .base_prefix :
105
+ if sys .prefix != sys .base_prefix and _do_i_own ( sys . prefix ) :
79
106
return True
80
107
81
108
# If sys.prefix indicates Python comes from a conda/mamba environment that is not the root environment, default to True
82
109
if (
83
110
"CONDA_PREFIX" in os .environ
84
111
and sys .prefix .startswith (os .environ ["CONDA_PREFIX" ])
85
112
and os .environ .get ("CONDA_DEFAULT_ENV" , "base" ) != "base"
113
+ and _do_i_own (sys .prefix )
86
114
):
87
115
return True
88
116
0 commit comments