jw.pkg.lib.util.get_profile_env(): add -> keep

Replace the boolean parameter "add" with the richer "keep":

  - False            -> Don't keep anything
  - True             -> Keep what's in the current environment
  - List of strings  -> Keep those variables

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-02-19 07:33:59 +01:00
commit b3fd624a3f

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from typing import Sequence from typing import Sequence, Iterable
import os, sys, subprocess, json, time, asyncio import os, sys, subprocess, json, time, asyncio
@ -299,10 +299,28 @@ async def get_password(args: Namespace|None=None, url: str|None=None, askpass_en
return parsed.password return parsed.password
return await run_askpass(askpass_env, AskpassKey.Password) return await run_askpass(askpass_env, AskpassKey.Password)
async def get_profile_env(throw: bool=True, add=False) -> dict[str, str]: # export async def get_profile_env(throw: bool=True, keep: Iterable[str]|bool=False) -> dict[str, str]: # export
env: dict[str,str]|None = None if add else {} """
# Run bash, source /etc/profile, then print environment as NUL-separated key=value pairs Get a fresh environment from /etc/profile
cmd = ['/bin/bash', '-lc', 'unset PROFILEREAD; source /etc/profile >/dev/null 2>&1; env -0']
Args:
keep:
- False -> Don't keep anything
- True -> Keep what's in the current environment
- List of strings -> Keep those variables
Returns:
Dictionary with fresh environment
"""
env: dict[str,str]|None = None
if keep == False or isinstance(keep, Iterable):
env = {
'HOME': os.environ.get('HOME', '/'),
'USER': os.environ.get('USER', ''),
'PATH': '/usr/bin:/bin',
}
# Run bash as a login shell, which sources /etc/profile, then print environment as NUL-separated key=value pairs
cmd = ['/usr/bin/env', '-i', '/bin/bash', '-lc', 'env -0']
stdout, stderr = await run_cmd(*cmd, throw=throw, output_encoding="bytes", verbose=True, env=env) stdout, stderr = await run_cmd(*cmd, throw=throw, output_encoding="bytes", verbose=True, env=env)
ret: dict[str, str] = {} ret: dict[str, str] = {}
for entry in stdout.split(b"\0"): for entry in stdout.split(b"\0"):
@ -310,4 +328,9 @@ async def get_profile_env(throw: bool=True, add=False) -> dict[str, str]: # expo
continue continue
key, val = entry.split(b"=", 1) key, val = entry.split(b"=", 1)
ret[key.decode()] = val.decode() ret[key.decode()] = val.decode()
if isinstance(keep, Iterable):
for key in keep:
val = os.getenv(key)
if val is not None:
ret[key] = val
return ret return ret