lib.ExecContext: Add open() + close() around _run()

Enclose ExecContext._run() in an open() / close() - pair. This is convenient for the caller in that it doesn't need to take care of opening and closing for one call only, and inconvenient in that it forces the caller to conciously add an open() / close() - pair around multiple run() calls where it wants the context to stay open in between. Or use the ExecContext as a context manager.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-04-25 08:29:55 +02:00
commit a9475de48e
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61
2 changed files with 41 additions and 36 deletions

View file

@ -287,22 +287,30 @@ class ExecContext(Base):
# be returned by CallContext and is very much allowed
assert cmd_input is not None, 'Invalid: cmd_input is None'
ret = Result(None, None, 1)
with self.CallContext(self, title=title, cmd=cmd, cmd_input=cmd_input, mod_env=mod_env, wd=wd,
log_prefix='|', throw=throw, verbose=verbose) as cc:
try:
ret = await self._run(
cmd = cc.cmd,
wd = wd,
verbose = cc.verbose,
cmd_input = cc.cmd_input,
mod_env = cc.mod_env,
interactive = cc.interactive,
log_prefix = cc.log_prefix
)
except Exception as e:
return cc.exception(ret, e)
cc.check_exit_code(ret)
# Enclose multiple run() calls in an additional open() / close() pair
# if you want the context to stay open between the calls
await self.open()
try:
ret = Result(None, None, 1)
with self.CallContext(self, title=title, cmd=cmd, cmd_input=cmd_input, mod_env=mod_env, wd=wd,
log_prefix='|', throw=throw, verbose=verbose) as cc:
try:
ret = await self._run(
cmd = cc.cmd,
wd = wd,
verbose = cc.verbose,
cmd_input = cc.cmd_input,
mod_env = cc.mod_env,
interactive = cc.interactive,
log_prefix = cc.log_prefix
)
except Exception as e:
return cc.exception(ret, e)
cc.check_exit_code(ret)
finally:
await self.close()
return ret
async def _sudo(
@ -482,10 +490,14 @@ class ExecContext(Base):
cmds.append({'cmd': ['chmod', mode, out]})
if atomic:
cmds.append({'cmd': ['mv', out, path]})
for cmd in cmds:
log(DEBUG, f'{self.log_name}: Running {pretty_cmd(cmd['cmd'], wd)}')
ret = await __run(**cmd)
return ret
await self.open()
try:
for cmd in cmds:
log(DEBUG, f'{self.log_name}: Running {pretty_cmd(cmd['cmd'], wd)}')
ret = await __run(**cmd)
return ret
finally:
await self.close()
except:
if throw:
raise