@@ -39,15 +39,30 @@ def is_running_user(cls) -> bool:
3939 @classmethod
4040 @functools .lru_cache (maxsize = 1 )
4141 def name (cls ) -> str :
42- return os .getenv ("USER" , pwd .getpwuid (cls .uid ).pw_name )
42+ try :
43+ return pwd .getpwuid (cls .uid ).pw_name
44+ except KeyError :
45+ if cls .uid == 0 :
46+ return "root"
47+
48+ if not (user := os .getenv ("USER" )):
49+ die (f"Could not find user name for UID { cls .uid } " )
50+
51+ return user
4352
4453 @classmethod
4554 @functools .lru_cache (maxsize = 1 )
4655 def home (cls ) -> Path :
4756 if cls .invoked_as_root and Path .cwd ().is_relative_to ("/home" ) and len (Path .cwd ().parents ) > 2 :
4857 return list (Path .cwd ().parents )[- 3 ]
4958
50- return Path (f"~{ cls .name ()} " ).expanduser ()
59+ try :
60+ return Path (pwd .getpwuid (cls .uid ).pw_dir or "/" )
61+ except KeyError :
62+ if not (home := os .getenv ("HOME" )):
63+ die (f"Could not find home directory for UID { cls .uid } " )
64+
65+ return Path (home )
5166
5267 @classmethod
5368 @functools .lru_cache (maxsize = 1 )
@@ -62,7 +77,11 @@ def is_regular_user(cls) -> bool:
6277 def cache_dir (cls ) -> Path :
6378 if (env := os .getenv ("XDG_CACHE_HOME" )) or (env := os .getenv ("CACHE_DIRECTORY" )):
6479 cache = Path (env )
65- elif cls .is_regular_user () and (Path .cwd ().is_relative_to (INVOKING_USER .home ()) or not cls .invoked_as_root ):
80+ elif (
81+ cls .is_regular_user () and
82+ INVOKING_USER .home () != Path ("/" ) and
83+ (Path .cwd ().is_relative_to (INVOKING_USER .home ()) or not cls .invoked_as_root )
84+ ):
6685 cache = INVOKING_USER .home () / ".cache"
6786 else :
6887 cache = Path ("/var/cache" )
0 commit comments