1
0

j2cfg code improvements

This commit is contained in:
Konstantin Demin 2024-07-25 11:11:44 +03:00
parent 8fac571d20
commit 48de90954f
Signed by: krd
GPG Key ID: 4D56F87A8BA65FD0

View File

@ -16,19 +16,19 @@ def is_mapping(x) -> bool:
return isinstance(x, collections.abc.Mapping)
def uniq(a: (list, set)) -> list:
return list(dict.fromkeys(a))
def uniq(a: list | set) -> list:
return sorted(set(a))
def remove_non_str(a: (list, set)) -> list:
def remove_non_str(a: list | set) -> list:
return list(filter(lambda x: isinstance(x, str), a))
def remove_empty_str(a: (list, set)) -> list:
def remove_empty_str(a: list | set) -> list:
return list(filter(None, a))
def uniq_str_list(a: (list, set)) -> (list, set):
def uniq_str_list(a: list | set) -> list:
return remove_empty_str(uniq(a))
@ -47,15 +47,14 @@ def dict_to_env_str_list(x: dict) -> list:
def any_to_str_list(x) -> list:
if x is None:
return []
if isinstance(x, str):
return [x]
if is_sequence(x):
return [str(e) for e in x]
if is_mapping(x):
return dict_to_env_str_list(x)
return [str(x)]
@ -130,21 +129,16 @@ def re_fullmatch_negate(x, pattern, flags=0):
def dict_remap_keys(x: dict, key_map) -> dict:
if key_map is None:
return x
all_keys = list(x.keys())
kmap = {
k: key_map(k)
for k in all_keys
if k != key_map(k)
}
persist_keys = [
k for k in all_keys
if k not in kmap.keys() and k not in kmap.values()
]
return {
k: x[k] for k in persist_keys
} | {
k: x[v] for k, v in kmap.items()
}
p = set(x.keys())
m = {}
for k in x:
v = key_map(k)
if v == k:
continue
m[k] = v
p.discard(k)
p.discard(v)
return {k: x[k] for k in p} | {v: x[k] for k, v in m.items()}
def re_sub(x, pattern, repl, count=0, flags=0):
@ -184,9 +178,11 @@ def any_to_env_dict(x) -> dict:
h = {}
def feed(k, v=None):
k = str(k)
def feed(k, parse=False, v=None):
if v is None:
return
k = str(k)
if parse:
k2, m, v2 = k.partition('=')
if m == '=':
k = k2
@ -200,13 +196,13 @@ def any_to_env_dict(x) -> dict:
h[k] = v if v is None else str(v)
if isinstance(x, str):
feed(x)
feed(x, True)
elif is_sequence(x):
for e in x:
feed(e)
feed(e, True)
elif is_mapping(x):
for k in x:
feed(k, x[k])
feed(k, False, x[k])
else:
return {}
@ -225,11 +221,11 @@ def dict_non_empty_keys(x: dict) -> list:
return sorted([k for k in x.keys() if x[k] is not None])
def list_diff(a: (list, set), b: (list, set)) -> list:
def list_diff(a: list | set, b: list | set) -> list:
return list(set(a) - set(b))
def list_intersect(a: (list, set), b: (list, set)) -> list:
def list_intersect(a: list | set, b: list | set) -> list:
return list(set(a) & set(b))