Makefile: Include py-topdir.mk

Include py-topdir.mk, which entails loads of fallout from make check.
Fix it.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-06-10 13:28:35 +02:00
commit e9845b5a1f
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61
44 changed files with 1796 additions and 1191 deletions

View file

@ -1,20 +1,17 @@
# -*- coding: utf-8 -*-
import argparse
from collections import OrderedDict
from .log import slog
from .log import get_caller_pos, slog
class ArgsContainer: # export
class ArgsContainer: # export
__args: OrderedDict[str, str] = OrderedDict()
__kwargs: OrderedDict[str, str] = OrderedDict()
__kwargs: OrderedDict[str, dict[str, str]] = OrderedDict()
__values: dict[str, str] = {}
__specified_args: list[str] = list()
def __getattr__(self, name):
values = self.__values
def __getattr__(self, name: str) -> str:
if name in self.__values:
return self.__values[name]
if name in self.__kwargs.keys():
@ -25,7 +22,7 @@ class ArgsContainer: # export
raise Exception(f'No argument "{name}" defined')
def __setattr__(self, name, value):
if not name in self.__kwargs.keys():
if name not in self.__kwargs.keys():
raise Exception(f'No argument "{name}" defined')
self.__values[name] = value
self.__specified_args.append(name)
@ -41,7 +38,7 @@ class ArgsContainer: # export
else:
raise Exception('Missing argument name')
name = name.replace('-', '_')
self.__args[name] = args
self.__args[name] = arg
self.__kwargs[name] = kwargs
def keys(self):
@ -50,7 +47,7 @@ class ArgsContainer: # export
def args(self, name) -> str:
return self.__args[name]
def kwargs(self, name) -> str:
def kwargs(self, name) -> dict[str, str]:
return self.__kwargs[name]
def dump(self, prio, *args, **kwargs):
@ -59,15 +56,17 @@ class ArgsContainer: # export
val = None
try:
val = self.__getattr__(name)
except:
except Exception:
pass
slog(prio, f'{name}: {val}', caller=caller)
slog(prio, f'{name}: {val}', caller = caller)
@property
def specified_args(self):
return self.__specified_args
def add_argument(p: argparse.ArgumentParser|ArgsContainer, name: str, *args, **kwargs): # export
def add_argument( # export
p: argparse.ArgumentParser | ArgsContainer, name: str, *args, **kwargs
):
key = name.strip('--').replace('-', '_')
if isinstance(p, ArgsContainer):

View file

@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
from typing import Any
class Bunch: # export
class Bunch: # export
def __init__(self, **kwargs):
self.__dict__.update(kwargs)

View file

@ -1,39 +1,49 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import inspect, sys, re, abc, argparse
from argparse import ArgumentParser, _SubParsersAction
import abc
import argparse
import inspect
import re
import sys
from argparse import ArgumentParser
from typing import TYPE_CHECKING
from . import log
if TYPE_CHECKING:
from .Cmds import Cmds
# full blown example of one level of nested subcommands
# git -C project remote -v show -n myremote
class Cmd(abc.ABC): # export
class Cmd(abc.ABC): # export
@abc.abstractmethod
async def run(self, args):
pass
def __init__(self, name: str, help: str) -> None:
from . import Cmds
self.name = name
self.help = help
self.parent = None
self.children: list[Cmd] = []
self.child_classes: list[type[Cmd]] = []
self.app: Cmds|None = None
self.app: Cmds | None = None
async def _run(self, args):
pass
def add_parser(self, parsers) -> ArgumentParser:
r = parsers.add_parser(self.name, help=self.help,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
r.set_defaults(func=self.run)
r = parsers.add_parser(
self.name,
help = self.help,
formatter_class = argparse.ArgumentDefaultsHelpFormatter
)
r.set_defaults(func = self.run)
return r
def add_subcommands(self, cmd: str|type[Cmd]|list[type[Cmd]]) -> None:
def add_subcommands(self, cmd: str | type[Cmd] | list[type[Cmd]]) -> None:
if isinstance(cmd, str):
sc = []
for name, obj in inspect.getmembers(sys.modules[self.__class__.__module__]):
@ -54,7 +64,7 @@ class Cmd(abc.ABC): # export
def add_arguments(self, parser: ArgumentParser) -> None:
pass
def conf_value(self, path, default=None):
def conf_value(self, path, default = None):
ret = None if self.app is None else self.app.conf_value(path, default)
if ret is None and default is not None:
return default

View file

@ -1,13 +1,21 @@
# -*- coding: utf-8 -*-
import argparse
import asyncio
import cProfile
import importlib
import inspect
import os
import re
import sys
import os, sys, argcomplete, argparse, importlib, inspect, re, pickle, asyncio, cProfile
from argparse import ArgumentParser
from pathlib import Path, PurePath
from .log import *
import argcomplete
from .log import DEBUG, ERR, NOTICE, add_log_file, set_flags, set_level, slog
from .stree import serdes
class Cmds: # export
class Cmds: # export
def __instantiate(self, cls):
try:
@ -15,7 +23,7 @@ class Cmds: # export
except Exception as e:
slog(ERR, f'Failed to instantiate command of type {cls}: {e}')
raise
r.cmds = self # TODO: Rename Cmds class to App, "Cmds" isn't very self-explanatory
r.cmds = self # TODO: Rename Cmds class to App, "Cmds" isn't self-explanatory
r.app = self
return r
@ -26,7 +34,9 @@ class Cmds: # export
for c in cmd.child_classes:
cmd.children.append(self.__instantiate(c))
if len(cmd.children) > 0:
subparsers = parser.add_subparsers(title='Available subcommands of ' + cmd.name, metavar='')
subparsers = parser.add_subparsers(
title = 'Available subcommands of ' + cmd.name, metavar = ''
)
for sub_cmd in cmd.children:
self.__add_cmd_to_parser(sub_cmd, subparsers)
@ -38,7 +48,13 @@ class Cmds: # export
slog(DEBUG, 'Reading configuration "{}"'.format(path))
return serdes.read(path, ''), [path]
def __init__(self, description: str = '', filter: str = '^Cmd.*', modules: None=None, eloop: None=None) -> None:
def __init__(
self,
description: str = '',
filter: str = '^Cmd.*',
modules: None = None,
eloop: None = None
) -> None:
self.__description = description
self.__filter = filter
self.__modules = modules
@ -68,18 +84,34 @@ class Cmds: # export
set_flags(log_flags)
set_level(log_level)
slog(DEBUG, "set log level to {}".format(log_level))
self.__parser = argparse.ArgumentParser(usage=os.path.basename(sys.argv[0]) + ' [options]',
formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=self.__description)
self.__parser.add_argument('--log-flags', help='Log flags', default=log_flags)
self.__parser.add_argument('--log-level', help='Log level', default=log_level)
self.__parser.add_argument('--backtrace', help='Show exception backtraces', action='store_true', default=False)
self.__parser.add_argument('--write-profile', help='Profile code and store output to file', default=None)
self.__parser.add_argument('--log-file', help='Log file', default=log_file)
if self.__modules == None:
self.__modules = [ '__main__' ]
self.__parser = argparse.ArgumentParser(
usage = os.path.basename(sys.argv[0]) + ' [options]',
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
description = self.__description
)
self.__parser.add_argument(
'--log-flags', help = 'Log flags', default = log_flags
)
self.__parser.add_argument(
'--log-level', help = 'Log level', default = log_level
)
self.__parser.add_argument(
'--backtrace',
help = 'Show exception backtraces',
action = 'store_true',
default = False
)
self.__parser.add_argument(
'--write-profile',
help = 'Profile code and store output to file',
default = None
)
self.__parser.add_argument('--log-file', help = 'Log file', default = log_file)
if self.__modules is None:
self.__modules = ['__main__']
subcmds = set()
slog(DEBUG, '-- searching for commands')
for m in self.__modules: # type: ignore
for m in self.__modules: # type: ignore
if m != '__main__':
importlib.import_module(m)
for name, c in inspect.getmembers(sys.modules[m], inspect.isclass):
@ -96,24 +128,27 @@ class Cmds: # export
subcmds.update(cmd.child_classes)
cmds = [cmd for cmd in self.__cmds if type(cmd) not in subcmds]
subparsers = self.__parser.add_subparsers(title='Available commands', metavar='')
subparsers = self.__parser.add_subparsers(
title = 'Available commands', metavar = ''
)
for cmd in cmds:
slog(DEBUG, f'Adding top-level command {cmd} to parser')
self.__add_cmd_to_parser(cmd, subparsers)
# Run all sub-commands. Overwrite if you want to do anything before or after
async def _run(self, argv=None):
async def _run(self, argv = None):
return await self.args.func(self.args)
async def __run(self, argv=None):
async def __run(self, argv = None):
argcomplete.autocomplete(self.__parser)
self.args = self.__parser.parse_args(args=argv)
self.args = self.__parser.parse_args(args = argv)
set_flags(self.args.log_flags)
set_level(self.args.log_level)
self.__back_trace = self.args.backtrace
exit_status = 0
# This is the toplevel parser, i.e. no func member has been added to the args via
# This is the toplevel parser, i.e. no func member has been added to the args
# yet, via
#
# Cmds.__init__()
# Cmds.__add_cmd_to_parser(cmd, subparsers)
@ -135,17 +170,15 @@ class Cmds: # export
add_log_file(self.args.log_file)
try:
ret = await self._run(self.args)
await self._run(self.args)
except Exception as e:
if hasattr(e, 'message'):
slog(ERR, e.message)
else:
slog(ERR, f'Exception: {type(e)}: {e}')
slog(ERR, f'Exception: {type(e)}: {str(e)}')
exit_status = 1
if self.__back_trace:
raise
finally:
if pr is not None:
assert self.args.write_profile is not None, 'args.write_profile'
pr.disable()
slog(NOTICE, f'Writing profile statistics to {self.args.write_profile}')
pr.dump_stats(self.args.write_profile)
@ -160,7 +193,7 @@ class Cmds: # export
self.eloop = None
self.__own_eloop = False
def conf_value(self, path, default=None):
def conf_value(self, path, default = None):
ret = None if self.__conf is None else self.__conf.value(path)
if ret is None and default is not None:
return default
@ -169,10 +202,12 @@ class Cmds: # export
def parser(self) -> ArgumentParser:
return self.__parser
def run(self, argv=None) -> None:
def run(self, argv = None) -> None:
#return self.__run()
return self.eloop.run_until_complete(self.__run(argv)) # type: ignore
return self.eloop.run_until_complete(self.__run(argv)) # type: ignore
def run_sub_commands(description = '', filter = '^Cmd.*', modules=None, argv=None): # export
def run_sub_commands( # export
description = '', filter = '^Cmd.*', modules = None, argv = None
):
cmds = Cmds(description, filter, modules)
return cmds.run(argv=argv)
return cmds.run(argv = argv)

View file

@ -1,14 +1,16 @@
# -*- coding: utf-8 -*-
import glob
import os
import re
import sys
from typing import Optional, Dict, cast
import os, re, glob, sys
from pathlib import Path, PosixPath
from pathlib import Path
from typing import Dict, Optional, cast
from . import stree
from .stree import serdes
from .log import DEBUG, ERR, slog, get_caller_pos
from .stree.StringTree import StringTree
from .log import *
class Config(): # export
class Config(): # export
def __load(self, search_dirs, glob_paths, refuse_mode_mask):
@ -33,15 +35,15 @@ class Config(): # export
for path in glob_paths:
dirs = search_dirs
if dirs is None:
dirs = [''] if __is_abs(path) else [ str(Path.home()), str(Path.cwd()) ]
dirs = [''] if __is_abs(path) else [str(Path.home()), str(Path.cwd())]
for d in dirs:
g = d + '/' + path if len(d) else path
slog(DEBUG, 'Looking for config "{}"'.format(g))
for f in glob.glob(g):
slog(DEBUG, 'Reading config "{}"'.format(f))
paths_buf = []
tree = stree.read(f, paths_buf=paths_buf)
assert(len(paths_buf))
tree = serdes.read(f, paths_buf = paths_buf)
assert (len(paths_buf))
if refuse_mode_mask is not None:
for p in paths_buf:
st = os.stat(p)
@ -49,37 +51,44 @@ class Config(): # export
for item in tree.child_list():
if item.content is None:
continue
if not re.search('password|secret', cast(str, item.content), flags=re.IGNORECASE):
if not re.search('password|secret',
cast('str', item.content),
flags = re.IGNORECASE):
continue
msg = "Config files define secret, but at least one has file permissions open for world"
msg = (
'Config files define secret, but at least one '
'has file permissions open for world'
)
slog(ERR, f'{msg}:')
for pp in paths_buf:
slog(ERR, f' {((os.stat(pp).st_mode) & 0o7777):o} {pp}')
mode = (os.stat(pp).st_mode) & 0o7777
slog(ERR, f' {mode:o} {pp}')
raise Exception(msg)
tree.dump(DEBUG, f)
ret.add("", tree)
return ret
def __init__(self,
search_dirs: Optional[list[str]]=None,
glob_paths: Optional[list[str]]=None,
glob_paths_env_key: Optional[str]=None,
defaults: Optional[Dict[str, str]]=None,
tree: Optional[StringTree]=None,
parent=None,
root_section=None,
refuse_mode_mask=0o0027
) -> None:
def __init__(
self,
search_dirs: Optional[list[str]] = None,
glob_paths: Optional[list[str]] = None,
glob_paths_env_key: Optional[str] = None,
defaults: Optional[Dict[str, str]] = None,
tree: Optional[StringTree] = None,
parent = None,
root_section = None,
refuse_mode_mask = 0o0027
) -> None:
self.__parent = parent
if tree is not None:
assert(search_dirs is None)
assert(glob_paths is None)
assert(glob_paths_env_key is None)
assert (search_dirs is None)
assert (glob_paths is None)
assert (glob_paths_env_key is None)
self.__conf = tree
else:
assert(tree is None)
assert (tree is None)
if glob_paths_env_key is not None:
glob_paths_env = os.getenv(glob_paths_env_key)
if glob_paths_env is not None:
@ -87,8 +96,11 @@ class Config(): # export
glob_paths = []
glob_paths.extend(glob_paths_env.split(':'))
self.__conf = self.__load(search_dirs=search_dirs, glob_paths=glob_paths,
refuse_mode_mask=refuse_mode_mask)
self.__conf = self.__load(
search_dirs = search_dirs,
glob_paths = glob_paths,
refuse_mode_mask = refuse_mode_mask
)
if root_section is not None:
tmp = self.__conf.get(root_section)
@ -141,7 +153,11 @@ class Config(): # export
def value(self, key: str, default = None) -> Optional[str]:
return self.get(key, default)
def branch(self, path: str, throw: bool=True): # type: ignore # Optional[Config]: FIXME: Don't know how to get hold of this type here
def branch(
self,
path: str,
throw: bool = True
): # type: ignore # Optional[Config]: FIXME: Don't know how to get hold of this type here
if self.__conf:
tree = self.__conf.get(path)
if tree is None:
@ -151,19 +167,24 @@ class Config(): # export
return None
self.dump(ERR, msg)
raise Exception(msg)
return Config(tree=tree, parent=self) # type: ignore
return Config(tree = tree, parent = self) # type: ignore
return None
def dump(self, prio: int, *args, **kwargs) -> None:
caller = get_caller_pos(1, kwargs)
self.__conf.dump(prio, caller=caller, *args, **kwargs)
self.__conf.dump(prio, caller = caller, *args, **kwargs)
@property
def name(self):
return self.__conf.content
def find(self, key: str|None, val: str|None, match:StringTree.Match=StringTree.Match.Equal) -> list[str]:
return self.__conf.find(key, val, match=match)
def find(
self,
key: str | None,
val: str | None,
match: StringTree.Match = StringTree.Match.Equal
) -> list[str]:
return self.__conf.find(key, val, match = match)
#def __getattr__(self, name: str):
# return getattr(self.__conf, name)

View file

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
class CppState: # export
class CppState: # export
def __init__(self):
self.__pair_square = ['[', ']']
@ -33,37 +31,39 @@ class CppState: # export
self.things.append(self.__pair_square)
elif tok == ']':
self.square -= 1
assert(self.things.pop() == self.__pair_square)
assert (self.things.pop() == self.__pair_square)
elif tok == '{':
self.curly += 1
self.things.append(self.__pair_curly)
elif tok == '}':
self.curly -= 1
assert(self.things.pop() == self.__pair_curly)
assert (self.things.pop() == self.__pair_curly)
elif tok == '(':
self.paren += 1
self.things.append(self.__pair_paren)
elif tok == ')':
self.paren -= 1
assert(self.things.pop() == self.__pair_paren)
assert (self.things.pop() == self.__pair_paren)
elif tok == '<':
self.ext += 1
self.things.append(self.__pair_ext)
elif tok == '>':
self.ext -= 1
assert(self.things.pop() == self.__pair_ext)
assert (self.things.pop() == self.__pair_ext)
elif tok == '?':
if not self.in_special:
self.in_special = True
self.things.append(self.__pair_special)
else:
self.in_special = False
assert(self.things.pop() == self.__pair_special)
assert (self.things.pop() == self.__pair_special)
elif tok == '/*':
self.in_c_comment = True
self.things.append(self.__pair_c_comment)
elif tok == '*/':
raise Exception("Unmatched closing C-style comment mark", tok, "in line", line)
raise Exception(
"Unmatched closing C-style comment mark", tok, "in line", line
)
else:
if self.in_cpp_comment:
if tok == '\n':
@ -72,7 +72,7 @@ class CppState: # export
if tok == '/*':
raise Exception("Nested C-style comment", tok, "in line", line)
elif tok == '*/':
assert(self.things.pop() == self.__pair_c_comment)
assert (self.things.pop() == self.__pair_c_comment)
self.in_c_comment = False
if self.curly < 0 or self.square < 0 or self.ext < 0 or self.paren < 0:
@ -101,4 +101,3 @@ class CppState: # export
def is_optional(self):
return self.in_list() or self.in_option()

View file

@ -1,6 +1,4 @@
TOPDIR = ../../../..
PY_UPDATE_INIT_PY ?= false
include $(TOPDIR)/make/proj.mk
include $(JWBDIR)/make/py-mod.mk

View file

@ -1,16 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import print_function
from . import log
class Object(object): # export
class Object(object): # export
def __init__(self):
self.log_level = log.level
self.log_level = log.log_level()
def log(self, prio, *args):
if self.log_level == log.level:
if self.log_level == log.log_level():
log.slog(prio, args)
return
if prio <= self.log_level:

View file

@ -1,11 +1,13 @@
import re
import json
from collections import OrderedDict
from .log import *
import re
import shlex
import traceback
class Options: # export
from collections import OrderedDict
from .log import ERR, get_caller_pos, slog, slog_m
class Options: # export
class OrderedData:
@ -30,8 +32,8 @@ class Options: # export
if spec[0] != '{':
spec = '{' + spec + '}'
try:
return json.loads(spec, object_pairs_hook=cls)
except:
return json.loads(spec, object_pairs_hook = cls)
except Exception:
pass
return None
@ -42,7 +44,7 @@ class Options: # export
r = cls()
try:
opt_strs = shlex.split(opts_str)
except Exception as e:
except Exception:
slog_m(ERR, traceback.format_exc())
slog(ERR, 'Failed to split options string >{}<'.format(opts_str))
raise
@ -52,7 +54,7 @@ class Options: # export
lhs = sides[0].strip()
if not len(lhs):
continue
if self.__allowed_keys and not lhs in self.__allowed_keys:
if self.__allowed_keys and lhs not in self.__allowed_keys:
raise Exception('Field "{}" not supported'.format(lhs))
rhs = ' '.join(sides[1:]).strip() if len(sides) > 1 else self.__true_val
if cls == OrderedDict:
@ -82,7 +84,7 @@ class Options: # export
self.__str = self.__str__()
def __getitem__(self, key):
if not key in self.__dict.keys():
if key not in self.__dict.keys():
return None
return self.__dict[key]
@ -99,35 +101,38 @@ class Options: # export
return len(self.__data.pairs)
def __contains__(self, keys):
if not type(keys) in [list, set]:
if type(keys) not in [list, set]:
return keys in self.__dict.keys()
for key in keys:
if not key in self.__dict.keys():
if key not in self.__dict.keys():
return False
return True
def __iter__(self):
return iter(self.__list)
def __next__(self):
return next(self.__list)
#def __next__(self):
# return next(self.__list)
def __init__(self, spec=None, delimiter=',', allowed_keys=None, true_val=True):
def __init__(
self, spec = None, delimiter = ',', allowed_keys = None, true_val = True
):
self.__true_val = true_val
self.__allowed_keys = None
self.__delimiter = delimiter
self.__data = self.OrderedData() if spec is None else self.__parse(spec, self.OrderedData)
self.__data = self.OrderedData(
) if spec is None else self.__parse(spec, self.OrderedData)
self.__dict = {}
#self.__dict = OrderedDict() if spec is None else self.__parse(spec, OrderedDict)
#self.__dict = OrderedDict() if spec is None else self.__parse(spec,OrderedDict)
self.__list = []
self.__str = None
self.__recache()
def dump(self, prio, caller=None):
def dump(self, prio, caller = None):
if caller is None:
caller = get_caller_pos()
for key, val in self.__data.pairs:
slog(prio, "{}=\"{}\"".format(key, val), caller=caller)
slog(prio, "{}=\"{}\"".format(key, val), caller = caller)
def keys(self):
return self.__dict.keys()
@ -136,22 +141,28 @@ class Options: # export
#return self.__dict.items()
return self.__data.pairs
def get(self, key, default=None, by_index=False):
def get(self, key, default = None, by_index = False):
if by_index:
if type(key) != int:
raise KeyError('Tried to get value from options string with ' +
'index {} of type "{}": {}'.format(key, type(key), str(self)))
if isinstance(key, int):
raise KeyError(
'Tried to get value from options string with ' +
'index {} of type "{}": {}'.format(key, type(key), str(self))
)
if key >= len(self.__data.pairs):
if default is not None:
return default
raise KeyError('Tried to get value from options string with ' +
'index {} of {}: {}'.format(key, len(self.__data.pairs), str(self)))
raise KeyError(
'Tried to get value from options string with ' +
'index {} of {}: {}'.format(key, len(self.__data.pairs), str(self))
)
return self.__list[key]
if key in self.__dict.keys():
return self.__dict[key]
if default is not None:
return default
raise KeyError('Key "{}" is not present in options string: {}'.format(key, str(self)))
raise KeyError(
'Key "{}" is not present in options string: {}'.format(key, str(self))
)
def update(self, rhs):
if hasattr(rhs, 'items'):
@ -159,9 +170,13 @@ class Options: # export
self.__dict[key] = val
return
if isinstance(rhs, str):
self.update(self.__parse(rhs))
self.update(self.__parse(rhs, self.OrderedData))
return
raise Exception('Tried to update options with object of incompatible type {}'.format(type(rhs)))
raise Exception(
'Tried to update options with object of incompatible type {}'.format(
type(rhs)
)
)
def append_to(self, obj):
for opt in self.__list:

View file

@ -1,41 +1,46 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import signal
from abc import ABC, abstractmethod
from enum import Enum, Flag, auto
from typing import List
from typing import TYPE_CHECKING
from .log import ERR, slog
if TYPE_CHECKING:
from .Signals import Signals
def _sigchld_handler(signum, process):
if not signum == signal.SIGCHLD:
return
Process.propagate_signal(signum)
class Process(ABC): # export
class Process(ABC): # export
__processes: List[Process] = []
__processes: set[Process] = set()
class State(Enum):
Running = auto()
Shutdown = auto()
Done = auto()
Running = auto()
Shutdown = auto()
Done = auto()
class Flags(Flag):
FailOnExitWithoutShutdown = auto()
def __init__(self):
self.__state = Running
self.__flags = Flags.FailOnExitWithoutShutdown
self.__state = Process.State.Running
self.__flags = self.Flags.FailOnExitWithoutShutdown
if len(self.__processes) == 0:
self._signals().add_handler(signals.SIGCHLD, _sigchld_handler)
self.signals().add_handler(signal.SIGCHLD, _sigchld_handler)
self.__processes.add(self)
@classmethod
def propagate_signal(cls, signum):
for p in cls.__processes:
p.__signal(signum)
cls.signals().propagate(signum)
def signal(self, signum):
if signum == signals.SIGCHLD:
if signum == signal.SIGCHLD:
self.exited()
@abstractmethod
@ -44,7 +49,7 @@ class Process(ABC): # export
@classmethod
@abstractmethod
def signals(cls):
def signals(cls) -> Signals:
pass
# to be reimplemented
@ -56,17 +61,15 @@ class Process(ABC): # export
return str(self._pid())
def request_shutdown(self):
if not self.__state == Shutdown:
self.__state = Shutdown
if not self.__state == Process.State.Shutdown:
self.__state = Process.State.Shutdown
self._request_shutdown()
def exited(self):
if self.__state == Process.State.Running:
slog(ERR, 'process "{}" exited unexpectedly'.format(process.name()))
if __flags & Process.Flags.FailOnExitWithoutShutdown:
slog(ERR, 'process exited unexpectedly')
if self.__flags & Process.Flags.FailOnExitWithoutShutdown:
slog(ERR, 'exiting')
exit(1)
self.__state = Process.State.Done
self.__processes.erase(self)
if len(self.__processes) == 0:
self._signals().remove_handler(signals.SIGCHLD) # FIXME: broken logic
self.__processes.remove(self)

View file

@ -1,13 +1,13 @@
# -*- coding: utf-8 -*-
from __future__ import print_function
import os, io, sys, traceback
import os
import io
import sys
from fcntl import fcntl, F_GETFL, F_SETFL
class RedirectStdIO: # export
class RedirectStdIO: # export
def __init__(self, stderr='on', stdout='off'):
def __init__(self, stderr = 'on', stdout = 'off'):
self.__stderr = stderr
self.__stdout = stdout
# TODO: arguments not fully implemented,
@ -30,12 +30,12 @@ class RedirectStdIO: # export
sys.stdout.flush()
os.dup2(self.real_stdout_fd, 1)
if type is not None:
#print("-------- Error while stdio was suppressed --------")
#traceback.print_stack()
#print(traceback)
print("-------- Captured output --------")
print(*self.rfile.readlines())
self.rfile.close()
#print('type = ' + str(type))
#print('value = ' + str(value))
raise type(value)
#print("-------- Error while stdio was suppressed --------")
#traceback.print_stack()
#print(traceback)
print("-------- Captured output --------")
print(*self.rfile.readlines())
self.rfile.close()
#print('type = ' + str(type))
#print('value = ' + str(value))
raise type(value)

View file

@ -1,19 +1,10 @@
# -*- coding: utf-8 -*-
from typing import Dict, Callable
from abc import ABC, abstractmethod
_handled_signals: Dict[int, Callable] = {}
def _signal_handler(signal, frame):
if not signal in _handled_signals.keys():
return
for h in _handled_signals[signal]:
h.func(signal, *h.args)
from abc import abstractmethod
from typing import Dict
class Signals:
class Handler:
def __init__(self, func, args):
self.func = func
self.args = args
@ -23,15 +14,27 @@ class Signals:
@classmethod
@abstractmethod
def _add_handler(self, signal, handler):
def _add_handler(cls, signal, handler):
raise Exception("_add_handler() is not reimplemented")
@classmethod
def add_handler(cls, signals, handler, *args):
for signal in signals:
h = Signals.Handler(handler, args)
if not signal in _handled_signals.keys():
if signal not in _handled_signals.keys():
_handled_signals[signal] = [h]
cls._add_signal_handler(signal, _signal_handler)
cls._add_handler(signal, _signal_handler)
else:
_handled_signals[signal].add(h)
_handled_signals[signal].append(h)
@classmethod
def propagate(cls, signal):
_signal_handler(signal, None)
_handled_signals: Dict[int, list[Signals.Handler]] = {}
def _signal_handler(signal, frame):
if signal not in _handled_signals.keys():
return
for h in _handled_signals[signal]:
h.func(signal, *h.args)

View file

@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
from datetime import datetime
from .log import *
from .log import get_caller_pos, slog
class StopWatch: # export
class StopWatch: # export
def __init__(self, name=''):
def __init__(self, name = ''):
self.__start = datetime.now()
self.__last = self.__start
self.name = name
@ -21,5 +19,9 @@ class StopWatch: # export
else:
msg = '------------------ '
caller = kwargs['caller'] if 'caller' in kwargs.keys() else get_caller_pos(1)
slog(prio, '{} {} {}'.format(self.name, str(now - self.__last), msg), caller=caller)
slog(
prio,
'{} {} {}'.format(self.name, str(now - self.__last), msg),
caller = caller
)
self.__last = now

View file

@ -1,3 +0,0 @@
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

View file

@ -1,16 +1,15 @@
# -*- coding: utf-8 -*-
import re
import re, shlex
from collections import namedtuple
from ..log import *
from ..log import DEBUG, get_caller_pos, prio_gets_logged, slog
L, R = 'Left Right'.split()
ARG, KEYW, QUOTED, LPAREN, RPAREN = 'arg kw quoted ( )'.split()
class Operator: # export
class Operator: # export
def __init__(self, func=None, nargs=2, precedence=3, assoc=L):
def __init__(self, func = None, nargs = 2, precedence = 3, assoc = L):
self.func = func
self.nargs = nargs
self.prec = precedence
@ -18,7 +17,7 @@ class Operator: # export
class Stack:
def __init__(self, itemlist=[]):
def __init__(self, itemlist = []):
self.items = itemlist
def __repr__(self):
@ -39,7 +38,7 @@ class Stack:
self.items.append(item)
return 0
class ShuntingYard(object): # export
class ShuntingYard(object): # export
def __init__(self, operators = None):
self.do_debug = prio_gets_logged(DEBUG)
@ -54,7 +53,7 @@ class ShuntingYard(object): # export
for count, thing in enumerate(args):
msg += ' ' + str(thing)
if len(msg):
slog(DEBUG, msg[1:], caller=get_caller_pos())
slog(DEBUG, msg[1:], caller = get_caller_pos())
def operator(self, key: str) -> Operator:
return self.__ops[key]
@ -65,7 +64,7 @@ class ShuntingYard(object): # export
v = self.__ops[k]
buf = ", \"" + k
if v.nargs == 1:
if k[len(k)-1].isalnum():
if k[len(k) - 1].isalnum():
buf = buf + ' '
buf = buf + "xxx"
buf = buf + "\""
@ -83,16 +82,20 @@ class ShuntingYard(object): # export
regex = regex[1:]
scanner = re.Scanner([
(regex, lambda scanner,token:(KEYW, token)),
(r"\"[^\"]*\"|'[^']*'", lambda scanner,token:(QUOTED, token[1:-1])),
(r"[^\s()]+", lambda scanner,token:(ARG, token)),
(r"\s+", None), # None == skip token.
])
scanner = re.Scanner( # pyright: ignore[reportAttributeAccessIssue]
[
(regex, lambda scanner, token: (KEYW, token)),
(r"\"[^\"]*\"|'[^']*'", lambda scanner, token: (QUOTED, token[1:-1])),
(r"[^\s()]+", lambda scanner, token: (ARG, token)),
(r"\s+", None), # None == skip token.
]
)
tokens, remainder = scanner.scan(spec)
if len(remainder)>0:
raise Exception("Failed to tokenize " + spec + ", remaining bit is ", remainder)
if len(remainder) > 0:
raise Exception(
"Failed to tokenize " + spec + ", remaining bit is ", remainder
)
#self.debug(tokens)
return tokens
@ -112,14 +115,14 @@ class ShuntingYard(object): # export
tokenized = self.tokenize(infix)
self.debug("tokenized = ", tokenized)
outq, stack = [], []
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
table = ['TOKEN', 'ACTION', 'RPN OUTPUT', ('OP STACK', ), 'NOTES']
for toktype, token in tokenized:
self.debug("Checking token", token)
note = action = ''
if toktype in [ ARG, QUOTED ]:
if toktype in [ARG, QUOTED]:
action = 'Add arg to output'
outq.append(token)
table.append( (token, action, outq, (s[0] for s in stack), note) )
table.append((token, action, outq, (s[0] for s in stack), note))
elif toktype == KEYW:
val = self.__ops[token]
t1, op1 = token, val
@ -127,7 +130,9 @@ class ShuntingYard(object): # export
note = 'Pop ops from stack to output'
while stack:
t2, op2 = stack[-1]
if (op1.assoc == L and op1.prec <= op2.prec) or (op1.assoc == R and op1.prec < op2.prec):
if (op1.assoc == L
and op1.prec <= op2.prec) or (op1.assoc == R
and op1.prec < op2.prec):
if t1 != RPAREN:
if t2 != LPAREN:
stack.pop()
@ -143,9 +148,11 @@ class ShuntingYard(object): # export
else:
stack.pop()
action = '(Pop & discard "(")'
table.append( (v, action, outq, (s[0] for s in stack), note) )
table.append(
(v, action, outq, (s[0] for s in stack), note)
)
break
table.append( (v, action, (outq), (s[0] for s in stack), note) )
table.append((v, action, (outq), (s[0] for s in stack), note))
v = note = ''
else:
note = ''
@ -157,7 +164,7 @@ class ShuntingYard(object): # export
action = 'Push op token to stack'
else:
action = 'Discard ")"'
table.append( (v, action, (outq), (s[0] for s in stack), note) )
table.append((v, action, (outq), (s[0] for s in stack), note))
note = 'Drain stack to output'
while stack:
v = ''
@ -165,15 +172,27 @@ class ShuntingYard(object): # export
action = '(Pop op)'
stack.pop()
outq.append(t2)
table.append( (v, action, outq, (s[0] for s in stack), note) )
table.append((v, action, outq, (s[0] for s in stack), note))
v = note = ''
if self.do_debug:
maxcolwidths = [len(max(x, key=len)) for x in [zip(*table)]]
caller = get_caller_pos()
maxcolwidths = [len(max(x, key = len)) for x in [zip(*table)]]
get_caller_pos()
row = table[0]
slog(DEBUG, ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
slog(
DEBUG,
' '.join(
'{cell:^{width}}'.format(width = width, cell = cell)
for (width, cell) in zip(maxcolwidths, row)
)
)
for row in table[1:]:
slog(DEBUG, ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
slog(
DEBUG,
' '.join(
'{cell:<{width}}'.format(width = width, cell = cell)
for (width, cell) in zip(maxcolwidths, row)
)
)
return table[-1][2]
def infix_to_postfix_orig(self, infix):
@ -185,7 +204,7 @@ class ShuntingYard(object): # export
for tokinfo in tokens:
self.debug(tokinfo)
toktype, token = tokinfo[0], tokinfo[1]
_toktype, token = tokinfo[0], tokinfo[1]
self.debug("Checking token ", token)
@ -204,7 +223,8 @@ class ShuntingYard(object): # export
topToken = s.pop()
continue
while (not s.isEmpty()) and (self.__ops[s.peek()].prec >= self.__ops[token].prec):
while (not s.isEmpty()) and (self.__ops[s.peek()].prec
>= self.__ops[token].prec):
#self.debug(token)
r.append(s.pop())
#self.debug(r)
@ -240,7 +260,9 @@ class ShuntingYard(object): # export
args.append(vals.pop())
#self.debug("running %s(%s)" % (token, ', '.join(reversed(args))))
val = op.func(*reversed(args))
self.debug("%s(%s) = %s" % (token, ', '.join(map(str, reversed(args))), val))
self.debug(
"%s(%s) = %s" % (token, ', '.join(map(str, reversed(args))), val)
)
vals.push(val)
return vals.pop()
@ -266,27 +288,27 @@ if __name__ == '__main__':
# return string.split()
def f_mult(self, a, b):
return str(atof(a) * atof(b));
return str(atof(a) * atof(b))
def f_div(self, a, b):
return str(atof(a) / atof(b));
return str(atof(a) / atof(b))
def f_add(self, a, b):
return str(atof(a) + atof(b));
return str(atof(a) + atof(b))
def f_sub(self, a, b):
return str(atof(a) - atof(b));
return str(atof(a) - atof(b))
def __init__(self):
Op = Operator
operators = {
'^': Op(None, 2, 4, R),
'^': Op(None, 2, 4, R),
'*': Op(self.f_mult, 2, 3, L),
'/': Op(self.f_div, 2, 3, L),
'+': Op(self.f_add, 2, 2, L),
'-': Op(self.f_sub, 2, 2, L),
'(': Op(None, 0, 9, L),
')': Op(None, 0, 0, L),
'/': Op(self.f_div, 2, 3, L),
'+': Op(self.f_add, 2, 2, L),
'-': Op(self.f_sub, 2, 2, L),
'(': Op(None, 0, 9, L),
')': Op(None, 0, 0, L),
}
super(Calculator, self).__init__(operators)
@ -295,7 +317,7 @@ if __name__ == '__main__':
# ------------- testbed match object
Object = namedtuple("Object", [ "Name", "Label" ])
Object = namedtuple("Object", ["Name", "Label"])
class Matcher(ShuntingYard):
@ -324,14 +346,14 @@ if __name__ == '__main__':
def __init__(self, obj):
Op = Operator
operators = {
'(': Op(None, 2, 9, L),
')': Op(None, 2, 0, L),
'name=': Op(self.f_is_name, 1, 3, R),
'and': Op(self.f_and, 2, 3, L),
'label~=': Op(self.f_matches_label, 1, 3, R),
'False': Op(None, 0, 3, L),
'True': Op(None, 0, 3, L),
'not': Op(self.f_is_not, 1, 3, R),
'(': Op(None, 2, 9, L),
')': Op(None, 2, 0, L),
'name=': Op(self.f_is_name, 1, 3, R),
'and': Op(self.f_and, 2, 3, L),
'label~=': Op(self.f_matches_label, 1, 3, R),
'False': Op(None, 0, 3, L),
'True': Op(None, 0, 3, L),
'not': Op(self.f_is_not, 1, 3, R),
}
super(Matcher, self).__init__(operators)

View file

@ -1,16 +1,14 @@
# -*- coding: utf-8 -*-
from abc import abstractmethod
from ..Process import Process as ProcessBase
from .Signals import Signals
class Process(ProcessBase): # export
class Process(ProcessBase): # export
__signals = Signals()
def __init__(self, aio):
super().__init()
super().__init__()
self.aio = aio
@classmethod

View file

@ -1,9 +1,11 @@
import asyncio
from ..log import *
import re
from ..log import DEBUG, ERR, INFO, WARNING, slog
# FIXME: Derive this from Process, or merge the classes entirely
class ShellCmd: # export
class ShellCmd: # export
class SubprocessProtocol(asyncio.SubprocessProtocol):
@ -26,12 +28,12 @@ class ShellCmd: # export
self.process.exited()
class ShutdownState:
Running = 1
Triggered = 2
Completed = 3
Running = 1
Triggered = 2
Completed = 3
Unnecessary = 4
def __init__(self, cmdline, eloop=None, name=None):
def __init__(self, cmdline, eloop = None, name = None):
if eloop is None:
eloop = asyncio.get_running_loop()
self.__eloop = eloop
@ -56,12 +58,19 @@ class ShellCmd: # export
return r[1:]
try:
slog(INFO, "Running shell command [{}]: {}".format(self.__name, format_cmdline(self.__cmdline)))
slog(
INFO,
"Running shell command [{}]: {}".format(
self.__name, format_cmdline(self.__cmdline)
)
)
self.__transport, self.__protocol = await self.__eloop.subprocess_exec(
lambda: self.SubprocessProtocol(self, self.__name),
*self.__cmdline,
)
self.__proc = self.__transport.get_extra_info('subprocess') # Popen instance
self.__proc = self.__transport.get_extra_info(
'subprocess'
) # Popen instance
except:
slog(ERR, "Failed to run process [{}]".format(self.__name))
raise
@ -69,7 +78,8 @@ class ShellCmd: # export
def __reap(self):
if self.__rc is None and self.__transport:
self.__transport = None
self.__rc = self.__proc.wait()
if self.__proc is not None:
self.__rc = self.__proc.wait()
# to be called from SubprocessProtocol / SIGCHLD handler
def exited(self):
@ -78,13 +88,24 @@ class ShellCmd: # export
async def __cleanup(self):
pid = self.__reap()
sd_fine = self.__shutdown in [ self.ShutdownState.Unnecessary, self.ShutdownState.Completed ]
sd_fine = self.__shutdown in [
self.ShutdownState.Unnecessary, self.ShutdownState.Completed
]
if self.__rc == 0 and sd_fine:
slog(INFO, "The shell command [{}], pid {}, has exited cleanly".format(self.__name, self.__proc.pid))
assert self.__proc is not None
slog(
INFO,
"The shell command [{}], pid {}, has exited cleanly".format(
self.__name, self.__proc.pid
)
)
self.monitor = self.console = self.__protocol = self.__task = None
return 0
slog(ERR, "The process ([{}], pid {}) has exited {}with status code {}, aborting".format(
self.__name, pid, "" if sd_fine else "prematurely ", self.__rc))
slog(
ERR,
"The process ([{}], pid {}) has exited {}with status code {}, aborting".
format(self.__name, pid, "" if sd_fine else "prematurely ", self.__rc)
)
exit(1)
async def init(self):
@ -100,9 +121,9 @@ class ShellCmd: # export
if __name__ == '__main__':
from .. import log
log.set_level('info')
async def run():
sp = ShellCmd([ 'echo', 'hello world!' ])
sp = ShellCmd(['echo', 'hello world!'])
await sp.run()
asyncio.run(run())

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import asyncio
from ..Signals import Signals as SignalsBase
@ -10,4 +8,4 @@ class Signals(SignalsBase):
@classmethod
def _add_handler(cls, signal, handler):
loop = asyncio.get_running_loop()
loop.add_signal_handler(signal, handler, None) # None = *args
loop.add_signal_handler(signal, handler, None) # None = *args

View file

@ -1,27 +1,28 @@
# -*- coding: utf-8 -*-
from typing import Optional, Union, Self
from __future__ import annotations
import abc
from enum import Flag, Enum, auto
from enum import Enum, Flag, auto
from typing import TYPE_CHECKING, Optional, Self, Union
from ..log import *
from ..Config import Config
from ..log import ERR
from ..misc import load_object
class Access(Enum): # export
Read = auto()
if TYPE_CHECKING:
from ..Config import Config
class Access(Enum): # export
Read = auto()
Modify = auto()
Create = auto()
Delete = auto()
class ProjectFlags(Flag): # export
NoFlags = auto()
class ProjectFlags(Flag): # export
NoFlags = auto()
Contributing = auto()
Active = auto()
Active = auto()
class Group: # export
class Group: # export
def __repr__(self):
return f'Group({self.name})'
@ -34,7 +35,7 @@ class Group: # export
def name(self) -> str:
return self._name()
class User: # export
class User: # export
def __repr__(self):
return f'User({self.name})'
@ -70,14 +71,14 @@ class User: # export
def email(self) -> str:
return self._email()
class Auth(abc.ABC): # export
class Auth(abc.ABC): # export
@classmethod
def load(cls, conf: Config, tp: str='') -> Self:
def load(cls, conf: Config, tp: str = '') -> Self:
if tp == '':
val = conf.get('type')
if val is None:
msg = f'No type specified in auth configuration'
msg = 'No type specified in auth configuration'
conf.dump(ERR, msg)
raise Exception(msg)
tp = val
@ -92,10 +93,17 @@ class Auth(abc.ABC): # export
return self.__conf
@abc.abstractmethod
def _access(self, what: str, access_type: Optional[Access], who: User|Group|None) -> bool:
def _access(
self, what: str, access_type: Optional[Access], who: User | Group | None
) -> bool:
raise NotImplementedError
def access(self, what: str, access_type: Optional[Access]=None, who: Optional[Union[User|Group]]=None) -> bool:
def access(
self,
what: str,
access_type: Optional[Access] = None,
who: Optional[Union[User, Group]] = None
) -> bool:
return self._access(what, access_type, who)
@abc.abstractmethod

View file

@ -1,16 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Optional, Union
from typing import TYPE_CHECKING, Optional
from ...log import *
from ... import Config
from .. import Access
from .. import Auth as AuthBase
from .. import Group as GroupBase
from .. import User as UserBase
from .. import ProjectFlags
from ...log import WARNING, slog
from ..Auth import Access
from ..Auth import Auth as AuthBase
from ..Auth import Group as GroupBase
from ..Auth import ProjectFlags
from ..Auth import User as UserBase
class Group(GroupBase): # export
if TYPE_CHECKING:
from ...Config import Config
class Group(GroupBase): # export
def __init__(self, auth: AuthBase, name: str):
self.__name = name
@ -19,7 +21,7 @@ class Group(GroupBase): # export
def _name(self) -> str:
return self.__name
class User(UserBase): # export
class User(UserBase): # export
def __init__(self, auth: AuthBase, name: str, conf: Config):
self.__name = name
@ -47,13 +49,13 @@ class User(UserBase): # export
def _email(self) -> str:
return self.__email
class Auth(AuthBase): # export
class Auth(AuthBase): # export
def __init__(self, conf: Config):
super().__init__(conf)
self.___users: Optional[dict[str, UserBase]] = None
self.__groups = None
self.__current_user: UserBase|None = None
self.__current_user: UserBase | None = None
self.__user_by_email: Optional[dict[str, UserBase]] = None
@property
@ -62,12 +64,18 @@ class Auth(AuthBase): # export
ret: dict[str, UserBase] = {}
for name in self.conf.entries('user'):
conf = self.conf.branch('user.' + name)
assert conf is not None, 'Config is None'
ret[name] = User(self, name, conf)
self.___users = ret
return self.___users
def _access(self, what: str, access_type: Optional[Access], who: User|GroupBase|None) -> bool: # type: ignore
slog(WARNING, f'Returning False for {access_type} access to resource {what} by {who}')
def _access(
self, what: str, access_type: Access | None, who: UserBase | GroupBase | None
) -> bool: # type: ignore
slog(
WARNING,
f'Returning False for {access_type} access to resource {what} by {who}'
)
return False
def _user(self, name) -> UserBase:

Some files were not shown because too many files have changed in this diff Show more