From b1d4e20295bc9e5df1fc1b0eaa1ce5d1799c8b10 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 17 Feb 2026 10:19:57 +0100 Subject: [PATCH] jw.pkg.util: Add sudo() Move the body of BackendCmd.sudo() into a function. The rationale behind that is that its functionality is independent of the calling object for the most part, so having it in a function instead of a method is the more modular pattern. Signed-off-by: Jan Lindemann --- .../jw/pkg/cmds/distro/backend/BackendCmd.py | 20 ++----------------- src/python/jw/pkg/lib/util.py | 18 +++++++++++++++++ 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/python/jw/pkg/cmds/distro/backend/BackendCmd.py b/src/python/jw/pkg/cmds/distro/backend/BackendCmd.py index 5a19360a..1be58030 100644 --- a/src/python/jw/pkg/cmds/distro/backend/BackendCmd.py +++ b/src/python/jw/pkg/cmds/distro/backend/BackendCmd.py @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- -import os - -from ....lib.util import run_cmd +from ....lib.util import run_cmd, run_sudo from ..Cmd import Cmd class BackendCmd: @@ -11,21 +9,7 @@ class BackendCmd: self.__parent = parent async def _sudo(self, cmd: list[str], mod_env: dict[str, str] = {}, opts: list[str]=[]): - env: dict[str, str]|None = None - cmd_input: str|None = None - if mod_env: - env = os.environ.copy() - env.update(mod_env) - cmdline = [] - if os.getuid() != 0: - cmdline.append('/usr/bin/sudo') - if env is not None: - cmdline.append('--preserve-env=' + ','.join(mod_env.keys())) - cmdline.extend(opts) - cmdline.extend(cmd) - if self.interactive: - cmd_input = "mode:interactive" - stdout, stderr = await run_cmd(*cmdline, throw=True, verbose=True, env=env, cmd_input=cmd_input) + return await run_sudo(cmd, mod_env=mod_env, opts=opts, interactive=self.interactive) @property def parent(self): diff --git a/src/python/jw/pkg/lib/util.py b/src/python/jw/pkg/lib/util.py index 8b74f665..8a6c2cc2 100644 --- a/src/python/jw/pkg/lib/util.py +++ b/src/python/jw/pkg/lib/util.py @@ -213,6 +213,24 @@ async def run_askpass(askpass_env: list[str], key: AskpassKey, host: str|None=No return ret return None +async def run_sudo(cmd: list[str], mod_env: dict[str, str] = {}, opts: list[str]=[], interactive: bool=True): + env: dict[str, str]|None = None + cmd_input: str|None = None + if mod_env: + env = os.environ.copy() + env.update(mod_env) + cmdline = [] + if os.getuid() != 0: + cmdline.append('/usr/bin/sudo') + if env is not None: + cmdline.append('--preserve-env=' + ','.join(mod_env.keys())) + cmdline.extend(opts) + cmdline.extend(cmd) + if interactive: + cmd_input = "mode:interactive" + stdout, stderr = await run_cmd(*cmdline, throw=True, verbose=True, env=env, cmd_input=cmd_input) + return stdout, stderr + async def get_username(args: Namespace|None=None, url: str|None=None, askpass_env: list[str]=[]) -> str: # export url_user = None if url is None else urlparse(url).username if args is not None: