lib.ec.ssh.AsyncSSH: Code beautification

Apply some style changes:

  - Replace double by single quotes for consistency

  - Add spaces around equal signs in long parameter lists

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-04-19 14:04:27 +02:00
commit f1898941e7

View file

@ -17,7 +17,7 @@ class AsyncSSH(Base):
uri: str, uri: str,
*, *,
client_keys: list[str] | None = None, client_keys: list[str] | None = None,
known_hosts=_USE_DEFAULT_KNOWN_HOSTS, known_hosts = _USE_DEFAULT_KNOWN_HOSTS,
term_type: str | None = None, term_type: str | None = None,
connect_timeout: float | None = 30.0, connect_timeout: float | None = 30.0,
**kwargs, **kwargs,
@ -25,28 +25,28 @@ class AsyncSSH(Base):
super().__init__( super().__init__(
uri, uri,
caps = self.Caps.LogOutput | self.Caps.Wd | self.Caps.Interactive | self.Caps.ModEnv, caps = self.Caps.LogOutput | self.Caps.Wd | self.Caps.Interactive | self.Caps.Env,
**kwargs **kwargs
) )
self.client_keys = client_keys self.client_keys = client_keys
self.known_hosts = known_hosts self.known_hosts = known_hosts
self.term_type = term_type or os.environ.get("TERM", "xterm") self.term_type = term_type or os.environ.get('TERM', 'xterm')
self.connect_timeout = connect_timeout self.connect_timeout = connect_timeout
def _connect_kwargs(self, hide_secrets: bool=False) -> dict: def _connect_kwargs(self, hide_secrets: bool=False) -> dict:
kwargs: dict = { kwargs: dict = {
"host": self.hostname, 'host': self.hostname,
"port": self.port, 'port': self.port,
"username": self.username, 'username': self.username,
"password": self.password, 'password': self.password,
"client_keys": self.client_keys, 'client_keys': self.client_keys,
"connect_timeout": self.connect_timeout, 'connect_timeout': self.connect_timeout,
} }
if self.known_hosts is not _USE_DEFAULT_KNOWN_HOSTS: if self.known_hosts is not _USE_DEFAULT_KNOWN_HOSTS:
kwargs["known_hosts"] = self.known_hosts kwargs['known_hosts'] = self.known_hosts
ret = {k: v for k, v in kwargs.items() if v is not None} ret = {k: v for k, v in kwargs.items() if v is not None}
if hide_secrets and 'password' in kwargs: if hide_secrets and 'password' in kwargs:
@ -57,13 +57,13 @@ class AsyncSSH(Base):
def _build_remote_command(cmd: list[str], wd: str | None) -> str: def _build_remote_command(cmd: list[str], wd: str | None) -> str:
if not cmd: if not cmd:
raise ValueError("cmd must not be empty") raise ValueError('cmd must not be empty')
inner = f"exec {join_cmd(cmd)}" inner = f'exec {join_cmd(cmd)}'
if wd is not None: if wd is not None:
inner = f"cd {shlex.quote(wd)} && {inner}" inner = f'cd {shlex.quote(wd)} && {inner}'
return f"/bin/sh -lc {shlex.quote(inner)}" return f'/bin/sh -lc {shlex.quote(inner)}'
@staticmethod @staticmethod
def _has_local_tty() -> bool: def _has_local_tty() -> bool:
@ -80,8 +80,8 @@ class AsyncSSH(Base):
try: try:
import fcntl, termios, struct import fcntl, termios, struct
packed = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, b"\0" * 8) packed = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, b'\0' * 8)
rows2, cols2, xpixel, ypixel = struct.unpack("HHHH", packed) rows2, cols2, xpixel, ypixel = struct.unpack('HHHH', packed)
if cols2 > 0 and rows2 > 0: if cols2 > 0 and rows2 > 0:
cols, rows = cols2, rows2 cols, rows = cols2, rows2
@ -100,7 +100,7 @@ class AsyncSSH(Base):
log_prefix: str, log_prefix: str,
log_enc: str, log_enc: str,
) -> None: ) -> None:
buf = b"" buf = b''
while True: while True:
chunk = await stream.read(4096) chunk = await stream.read(4096)
@ -111,12 +111,12 @@ class AsyncSSH(Base):
if verbose: if verbose:
buf += chunk buf += chunk
while b"\n" in buf: while b'\n' in buf:
line, buf = buf.split(b"\n", 1) line, buf = buf.split(b'\n', 1)
log(prio, log_prefix, line.decode(log_enc, errors="replace")) log(prio, log_prefix, line.decode(log_enc, errors='replace'))
if verbose and buf: if verbose and buf:
log(prio, log_prefix, buf.decode(log_enc, errors="replace")) log(prio, log_prefix, buf.decode(log_enc, errors='replace'))
async def _run_interactive_on_conn( async def _run_interactive_on_conn(
self, self,
@ -131,15 +131,15 @@ class AsyncSSH(Base):
stdout_parts: list[bytes] = [] stdout_parts: list[bytes] = []
proc = await conn.create_process( proc = await conn.create_process(
command=command, command = command,
env=mod_env, env = mod_env,
stdin=asyncssh.PIPE, stdin = asyncssh.PIPE,
stdout=asyncssh.PIPE, stdout = asyncssh.PIPE,
stderr=asyncssh.STDOUT, stderr = asyncssh.STDOUT,
encoding=None, encoding = None,
request_pty="force", request_pty = 'force',
term_type=self.term_type, term_type = self.term_type,
term_size=self._get_local_term_size(), term_size = self._get_local_term_size(),
) )
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
@ -161,7 +161,7 @@ class AsyncSSH(Base):
try: try:
data = os.read(stdin_fd, 4096) data = os.read(stdin_fd, 4096)
except OSError: except OSError:
data = b"" data = b''
if data: if data:
stdin_queue.put_nowait(data) stdin_queue.put_nowait(data)
@ -223,7 +223,7 @@ class AsyncSSH(Base):
except (NotImplementedError, RuntimeError): except (NotImplementedError, RuntimeError):
stdin_queue.put_nowait(None) stdin_queue.put_nowait(None)
if hasattr(signal, "SIGWINCH"): if hasattr(signal, 'SIGWINCH'):
try: try:
old_winch_handler = signal.getsignal(signal.SIGWINCH) old_winch_handler = signal.getsignal(signal.SIGWINCH)
signal.signal(signal.SIGWINCH, _on_winch) signal.signal(signal.SIGWINCH, _on_winch)
@ -233,7 +233,7 @@ class AsyncSSH(Base):
stdin_task = asyncio.create_task(_pump_stdin()) stdin_task = asyncio.create_task(_pump_stdin())
stdout_task = asyncio.create_task(_pump_stdout()) stdout_task = asyncio.create_task(_pump_stdout())
completed = await proc.wait(check=False) completed = await proc.wait(check = False)
await stdout_task await stdout_task
if not stdin_task.done(): if not stdin_task.done():
@ -247,7 +247,7 @@ class AsyncSSH(Base):
if exit_code is None: if exit_code is None:
exit_code = completed.returncode if completed.returncode is not None else -1 exit_code = completed.returncode if completed.returncode is not None else -1
stdout = b"".join(stdout_parts) if stdout_parts else None stdout = b''.join(stdout_parts) if stdout_parts else None
return Result(stdout, None, exit_code) return Result(stdout, None, exit_code)
finally: finally:
@ -257,7 +257,7 @@ class AsyncSSH(Base):
except Exception: except Exception:
pass pass
if old_winch_handler is not None and hasattr(signal, "SIGWINCH"): if old_winch_handler is not None and hasattr(signal, 'SIGWINCH'):
try: try:
signal.signal(signal.SIGWINCH, old_winch_handler) signal.signal(signal.SIGWINCH, old_winch_handler)
except Exception: except Exception:
@ -289,17 +289,17 @@ class AsyncSSH(Base):
command = self._build_remote_command(cmd, wd) command = self._build_remote_command(cmd, wd)
stdout_parts: list[bytes] = [] stdout_parts: list[bytes] = []
stdout_log_enc = sys.stdout.encoding or "utf-8" stdout_log_enc = sys.stdout.encoding or 'utf-8'
proc = await conn.create_process( proc = await conn.create_process(
command=command, command = command,
env=mod_env, env = mod_env,
stdin=asyncssh.PIPE if cmd_input is not None else asyncssh.DEVNULL, stdin = asyncssh.PIPE if cmd_input is not None else asyncssh.DEVNULL,
stdout=asyncssh.PIPE, stdout = asyncssh.PIPE,
stderr=asyncssh.STDOUT, stderr = asyncssh.STDOUT,
encoding=None, encoding = None,
request_pty="force", request_pty = 'force',
term_type=self.term_type, term_type = self.term_type,
) )
task = asyncio.create_task( task = asyncio.create_task(
@ -307,9 +307,9 @@ class AsyncSSH(Base):
proc.stdout, proc.stdout,
NOTICE, NOTICE,
stdout_parts, stdout_parts,
verbose=verbose, verbose = verbose,
log_prefix=log_prefix, log_prefix = log_prefix,
log_enc=stdout_log_enc, log_enc = stdout_log_enc,
) )
) )
@ -325,7 +325,7 @@ class AsyncSSH(Base):
if exit_code is None: if exit_code is None:
exit_code = completed.returncode if completed.returncode is not None else -1 exit_code = completed.returncode if completed.returncode is not None else -1
stdout = b"".join(stdout_parts) if stdout_parts else None stdout = b''.join(stdout_parts) if stdout_parts else None
return Result(stdout, None, exit_code) return Result(stdout, None, exit_code)
async def _run_on_conn( async def _run_on_conn(
@ -342,21 +342,21 @@ class AsyncSSH(Base):
if interactive: if interactive:
if self._has_local_tty(): if self._has_local_tty():
return await self._run_interactive_on_conn( return await self._run_interactive_on_conn(
conn=conn, conn = conn,
cmd=cmd, cmd = cmd,
wd=wd, wd = wd,
cmd_input=cmd_input, cmd_input = cmd_input,
mod_env=mod_env, mod_env = mod_env,
) )
return await self._run_captured_pty_on_conn( return await self._run_captured_pty_on_conn(
conn=conn, conn = conn,
cmd=cmd, cmd = cmd,
wd=wd, wd = wd,
verbose=verbose, verbose = verbose,
cmd_input=cmd_input, cmd_input = cmd_input,
mod_env=mod_env, mod_env = mod_env,
log_prefix=log_prefix, log_prefix = log_prefix,
) )
command = self._build_remote_command(cmd, wd) command = self._build_remote_command(cmd, wd)
@ -364,19 +364,19 @@ class AsyncSSH(Base):
stdout_parts: list[bytes] = [] stdout_parts: list[bytes] = []
stderr_parts: list[bytes] = [] stderr_parts: list[bytes] = []
stdout_log_enc = sys.stdout.encoding or "utf-8" stdout_log_enc = sys.stdout.encoding or 'utf-8'
stderr_log_enc = sys.stderr.encoding or "utf-8" stderr_log_enc = sys.stderr.encoding or 'utf-8'
stdin_mode = asyncssh.PIPE if cmd_input is not None else asyncssh.DEVNULL stdin_mode = asyncssh.PIPE if cmd_input is not None else asyncssh.DEVNULL
proc = await conn.create_process( proc = await conn.create_process(
command=command, command = command,
env=mod_env, env = mod_env,
stdin=stdin_mode, stdin = stdin_mode,
stdout=asyncssh.PIPE, stdout = asyncssh.PIPE,
stderr=asyncssh.PIPE, stderr = asyncssh.PIPE,
encoding=None, encoding = None,
request_pty=False, request_pty = False,
) )
tasks = [ tasks = [
@ -385,9 +385,9 @@ class AsyncSSH(Base):
proc.stdout, proc.stdout,
NOTICE, NOTICE,
stdout_parts, stdout_parts,
verbose=verbose, verbose = verbose,
log_prefix=log_prefix, log_prefix = log_prefix,
log_enc=stdout_log_enc, log_enc = stdout_log_enc,
) )
), ),
asyncio.create_task( asyncio.create_task(
@ -395,9 +395,9 @@ class AsyncSSH(Base):
proc.stderr, proc.stderr,
ERR, ERR,
stderr_parts, stderr_parts,
verbose=verbose, verbose = verbose,
log_prefix=log_prefix, log_prefix = log_prefix,
log_enc=stderr_log_enc, log_enc = stderr_log_enc,
) )
), ),
] ]
@ -410,8 +410,8 @@ class AsyncSSH(Base):
completed = await proc.wait(check=False) completed = await proc.wait(check=False)
await asyncio.gather(*tasks) await asyncio.gather(*tasks)
stdout = b"".join(stdout_parts) if stdout_parts else None stdout = b''.join(stdout_parts) if stdout_parts else None
stderr = b"".join(stderr_parts) if stderr_parts else None stderr = b''.join(stderr_parts) if stderr_parts else None
exit_code = completed.exit_status exit_code = completed.exit_status
if exit_code is None: if exit_code is None:
@ -432,14 +432,14 @@ class AsyncSSH(Base):
try: try:
async with asyncssh.connect(**self._connect_kwargs()) as conn: async with asyncssh.connect(**self._connect_kwargs()) as conn:
return await self._run_on_conn( return await self._run_on_conn(
conn=conn, conn = conn,
cmd=cmd, cmd = cmd,
wd=wd, wd = wd,
verbose=verbose, verbose = verbose,
cmd_input=cmd_input, cmd_input = cmd_input,
mod_env=mod_env, mod_env = mod_env,
interactive=interactive, interactive = interactive,
log_prefix=log_prefix, log_prefix = log_prefix,
) )
except Exception as e: except Exception as e:
msg = f'-------------------- Failed to run command {" ".join(cmd)} ({e})' msg = f'-------------------- Failed to run command {" ".join(cmd)} ({e})'