jw.pkg: Fix "make check" static code check fallout
The previous commits have put rules for linting and formatting via ruff, yapf, mypy and pyright into place. They are checked with the make check target, and this commit adds the fixes for the target to succeed.
It does some refactoring where type checking dug up dirty bits, and also adds lots of churn in the Python code. To a good deal, that's owed to mere formatting changes. It would have been better to seperate those from syntax and refactoring fixes into multiple commits, so that the interesting changes don't drown in the formatting nose. However, that would have been a lot of additional work only to be thrown away by later commits, hence this commit has a big diff in one piece. The size of the diff is regrettable but hopefully a one-off: What it buys is automatic format checking for CI and predictble formats for smaller diffs in the future.
Rules that "make check" enforces are, in the following order
- Syntax checkers:
- ruff check . - mypy . - pyright- Format check:
- yapf --diff --recursive .The refactoring includes:
- Turn the Result class into a more elaborate object, capable of doing more heavy lifting around stderr and stdout decoding, summarizing outcome, and matching error strings.Aside from fixing broken type checks, this also removes lots of boilerplate calling code which is currently used for handling possible call outcome scenarios. Trying to access an inexistent, decoded string should raise a meaningful exception by itself now, which removes lots of code with case distinctions.- Fix Cmd type hierarchy:
- Add the AbstractCmd class above Cmd. This is necessary because the checker rightfully complains it can't instantiate a Cmd instance where constructor arguments were needed. They never were, but the type used at the instantiating code's location in jw.pkg.App so claims.- Lots of sub- and sub-subcommands are derived from the base class of the invoking command. That provides some properties shared across the ancestor hierarchy of a command, but is semantically unsound. Fix that by introducing jw.pkg.BaseCmd class as a place to provide basic helpers shared across all commands used in a jw.pkg.App's context, and derive all command classes from that afresh. The parent command is still reachable via a common parent property.Formatting changes are conforming to PEP-8, mostly, with minor tweaks. All in all they include the following changes.
- Remove # -*- coding: utf-8 -*-
The line was needed by Python 2 which is not supported anylonger. For Python 3, the default encoding is UTF-8, anyway.- Allow to run "make py-format" without having it produce any changes. It's basically "yapf --in-place --recursive ." with some code style settings, see conf/topdir/pyproject.toml. The settings may be debatable. I've had custom tweaks in place on that target, too, but then again, IDEs would have more hassle to integrate that.- Introduce a 88 character line length limit
- One import per line, reshuffle them semantically, see [tool.isort] in pyproject.toml.- Hide imports needed for type-checking only behind
if TYPE_CHECKING- Spaces around assignments accounts for much churn. Having having no spaces in inline parameter list assignments and default parameter values would arguably be more compact where it's useful. On the other hand, I have not found a code formatter which allows spaces around assignments in parameter lists broken into one per line and that's often better than a wall of text.- Add two spaces before # export, as this seems to be mandated by PEP-8- Use single quotes by default
Signed-off-by: Jan Lindemann <jan@janware.com>
|
|
@ -1,29 +1,34 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Self
|
||||
|
||||
import abc, io
|
||||
import abc
|
||||
import io
|
||||
import tarfile
|
||||
from tarfile import TarFile
|
||||
|
||||
from tarfile import TarFile, TarInfo
|
||||
|
||||
from .base import StatResult
|
||||
from .CopyContext import CopyContext
|
||||
from .FileContext import FileContext
|
||||
from .log import *
|
||||
from .ExecContext import ExecContext
|
||||
from .log import DEBUG, ERR, log
|
||||
|
||||
class TarIo(CopyContext):
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs, chroot=False)
|
||||
kwargs['chroot'] = False
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def _match(self, path: str, path_filter: list[str]) -> bool:
|
||||
return path in path_filter
|
||||
|
||||
def _filter_tar_file(self, blob: bytes, path_filter: list[str]|None=None, matched: list[str]|None=None) -> bytes:
|
||||
def _filter_tar_file(
|
||||
self,
|
||||
blob: bytes,
|
||||
path_filter: list[str] | None = None,
|
||||
matched: list[str] | None = None,
|
||||
) -> bytes:
|
||||
ret = io.BytesIO()
|
||||
with tarfile.open(fileobj=ret, mode='w') as tf_out:
|
||||
tf_in = TarFile(fileobj=io.BytesIO(blob))
|
||||
with tarfile.open(fileobj = ret, mode = 'w') as tf_out:
|
||||
tf_in = TarFile(fileobj = io.BytesIO(blob))
|
||||
for info in tf_in.getmembers():
|
||||
if path_filter is not None and not self._match(info.name, path_filter):
|
||||
continue
|
||||
|
|
@ -34,13 +39,18 @@ class TarIo(CopyContext):
|
|||
tf_out.addfile(info, buf)
|
||||
return ret.getvalue()
|
||||
|
||||
async def _read_filtered(self, path, path_filter: list[str]|None=None, matched: list[str]|None=None) -> bytes:
|
||||
async def _read_filtered(
|
||||
self,
|
||||
path,
|
||||
path_filter: list[str] | None = None,
|
||||
matched: list[str] | None = None,
|
||||
) -> bytes:
|
||||
try:
|
||||
blob = (await self.src.get(path)).stdout
|
||||
except Exception as e:
|
||||
log(ERR, f'Failed to read tar file "{path}" ({str(e)}')
|
||||
raise
|
||||
return self._filter_tar_file(blob, path_filter, matched=matched)
|
||||
return self._filter_tar_file(blob, path_filter, matched = matched)
|
||||
|
||||
def _add(self, tf: TarFile, path: str, st: StatResult, contents: bytes) -> None:
|
||||
file_obj = io.BytesIO(contents)
|
||||
|
|
@ -50,37 +60,34 @@ class TarIo(CopyContext):
|
|||
info.uname = st.owner
|
||||
info.gname = st.group
|
||||
info.size = st.size
|
||||
info.atime = st.atime
|
||||
info.mtime = st.mtime
|
||||
info.ctime = st.ctime
|
||||
tf.addfile(info, io.BytesIO(file_obj))
|
||||
|
||||
async def _add_from_path(self, src: FileContext, tf: TarFile, path: str) -> None:
|
||||
contents = await src.get(path)
|
||||
st = await self.stat(path)
|
||||
self._add(tf, path, st, contents)
|
||||
info.mtime = int(st.mtime)
|
||||
tf.addfile(info, file_obj)
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _extract(self, blob: bytes, root: str|None=None) -> None:
|
||||
async def _extract(self, blob: bytes, root: str | None = None) -> None:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def extract(self, root: str|None=None, path_filter: list[str]|None=None) -> list[str]:
|
||||
async def extract(
|
||||
self,
|
||||
root: str | None = None,
|
||||
path_filter: list[str] | None = None
|
||||
) -> list[str]:
|
||||
ret: list[str] = []
|
||||
filtered = await self._read_filtered(self.src.root, path_filter, matched=ret)
|
||||
await self._extract(blob=filtered, root=root)
|
||||
filtered = await self._read_filtered(self.src.root, path_filter, matched = ret)
|
||||
await self._extract(blob = filtered, root = root)
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def create(cls, *args, type: str=None, **kwargs):
|
||||
def create(cls, *args, type: str | None = None, **kwargs):
|
||||
if type is not None:
|
||||
raise NotImplementedError
|
||||
#return TarIoTarFile(*args, **kwargs)
|
||||
# return TarIoTarFile(*args, **kwargs)
|
||||
return TarIoTarExec(*args, **kwargs)
|
||||
|
||||
class TarIoTarFile(TarIo):
|
||||
|
||||
async def _extract(self, blob: bytes, root: str|None=None) -> None:
|
||||
tf = TarFile(fileobj=io.BytesIO(blob))
|
||||
async def _extract(self, blob: bytes, root: str | None = None) -> None:
|
||||
tf = TarFile(fileobj = io.BytesIO(blob))
|
||||
for info in tf.getmembers():
|
||||
log(DEBUG, f'Extracting {info.name}')
|
||||
path = root + '/' + info.name if root else info.name
|
||||
|
|
@ -96,14 +103,24 @@ class TarIoTarFile(TarIo):
|
|||
buf.read(),
|
||||
owner = info.uname,
|
||||
group = info.gname,
|
||||
mode = info.mode,
|
||||
mode = info.mode,
|
||||
)
|
||||
|
||||
class TarIoTarExec(TarIo):
|
||||
|
||||
async def _extract(self, blob: bytes, root: str|None=None) -> None:
|
||||
@property
|
||||
def dst(self) -> ExecContext:
|
||||
ret = super().dst
|
||||
if not isinstance(ret, ExecContext):
|
||||
raise Exception(
|
||||
'Tried to get executable destination context from copy '
|
||||
'context, which only has a file context'
|
||||
)
|
||||
return ret
|
||||
|
||||
async def _extract(self, blob: bytes, root: str | None = None) -> None:
|
||||
cmd = ['tar']
|
||||
if root is not None:
|
||||
cmd += ['-C', root]
|
||||
cmd += ['-x', '-f', '-']
|
||||
await self.dst.run(cmd, cmd_input=blob)
|
||||
await self.dst.run(cmd, cmd_input = blob)
|
||||
|
|
|
|||