File: //var/opt/nydus/ops/customer_local_ops/util/__init__.py
from base64 import b64encode
import functools
import random
import string
def b64str(s: str) -> str:
"""Return `s` base64-encoded.
:param s: string to encode
"""
return b64encode(s.encode()).decode()
def fmap(func, obj):
"Homomorphic mapping of a function"
# strings are specifically not fmap-able because that invites
# consideration as byte characters, not unicode
if isinstance(obj, tuple):
return tuple(map(functools.partial(fmap, func), obj))
iterableitems = isinstance(obj, (list, dict))
if not iterableitems:
try:
iterableitems = isinstance(obj, (filter, map, zip, range))
except TypeError: # pragma: nocover
# Python2 doesn't have objects like the above
# The corresponding operations just result in lists
# which is already covered
pass
if iterableitems:
if hasattr(obj, 'items'):
return dict(map(functools.partial(fmap, func), obj.items()))
return list(map(functools.partial(fmap, func), obj))
if hasattr(obj, 'fmap'):
return obj.fmap(func)
return func(obj)
def random_password(length: int = None) -> str:
"""Create a random password.
:param length: An int specifying password length
:returns: the password, in cleartext
"""
if not length:
length = random.randint(10, 23)
edited_punctuation = string.punctuation.replace('"', '').replace("'", "").replace("\\", "")
return ''.join([random.choice(string.digits + string.ascii_letters + edited_punctuation)
for X in range(length)])