From b3fd624a3f106cb956f7833da3367ad306f82efe Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 19 Feb 2026 07:33:59 +0100 Subject: [PATCH] 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 --- src/python/jw/pkg/lib/util.py | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/src/python/jw/pkg/lib/util.py b/src/python/jw/pkg/lib/util.py index 90299fe6..6d4efc3a 100644 --- a/src/python/jw/pkg/lib/util.py +++ b/src/python/jw/pkg/lib/util.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from typing import Sequence +from typing import Sequence, Iterable 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 await run_askpass(askpass_env, AskpassKey.Password) -async def get_profile_env(throw: bool=True, add=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 - cmd = ['/bin/bash', '-lc', 'unset PROFILEREAD; source /etc/profile >/dev/null 2>&1; env -0'] +async def get_profile_env(throw: bool=True, keep: Iterable[str]|bool=False) -> dict[str, str]: # export + """ + Get a fresh environment from /etc/profile + + 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) ret: dict[str, str] = {} 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 key, val = entry.split(b"=", 1) 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