3 from functools
import lru_cache
5 from pathlib
import Path
7 from typing
import Mapping
10 "DBUS_SESSION_BUS_ADDRESS",
16 "XDG_CURRENT_DESKTOP",
19 ALLOWED_ENV_VARS
= ENV_VARS_TO_DUMP
+ [
24 USER_ENV_FILE_TEMPLATE
= "/run/user/{uid}/user-env"
27 def user_env_file(uid
):
28 return USER_ENV_FILE_TEMPLATE
.format(uid
=uid
)
31 def allowed_env(env
: Mapping
) -> dict:
33 >>> allowed_env({"PATH": "/home/", "LANG": "en"})
36 return {key
: value
for key
, value
in env
.items() if key
in ALLOWED_ENV_VARS
}
39 def read_allowed_env_from_file(envfile
: str) -> dict:
42 for line
in Path(envfile
).read_text().split('\0'):
47 key
, value
= line
.split("=", 1)
48 except Exception as e
:
49 print(f
"Invalid environment variable: '{line}'", file=sys
.stderr
)
54 return allowed_env(env
)
58 def read_user_env(user
=None) -> dict:
62 uid
= pwd
.getpwnam(user
).pw_uid
64 return read_allowed_env_from_file(user_env_file(uid
))
67 def user_env_vars(user
=None) -> list:
68 return [f
"{key}={value}" for key
, value
in read_user_env(user
).items()]