"""Some various utilities."""
from __future__ import annotations
from os.path import join, normpath, isdir
# =============================================================================
[docs]
def location2abs_base(locations: dict, location_id: str) -> str | None:
"""Return the absolute path to the base of location ``location_id``.
:pram dict locations:
Dictionary of locations. It can be updated during the operation.
:param str location_id:
ID of the searched location. A named location is like ``'private'``,
a workspace is like ``'Sandbox'``.
:rtype: :class:`str` or ``None``
"""
if not location_id:
return None
if location_id[0] == '/':
location_id = location_id[1:]
if location_id in locations:
return locations[location_id]
for loc_id in locations:
base = join(locations[loc_id], location_id)
if isdir(base):
locations[location_id] = base
return base
return None
# =============================================================================
[docs]
def location_path2abs_path(locations: dict, location_path: str) -> str | None:
"""Return an absolute path for a location path using the dictionary of
locations. A location path must contain ``':'`` (``'private:MyDocument'``)
and can begin with ``'/'`` (``'/Sandbox:Images/foo.png'``).
:pram dict locations:
Dictionary of locations. It can be updated during the operation.
:param str path:
Location path.
:rtype: class:`str` or ``None``
"""
if not location_path or ':' not in location_path:
return None
location_id, path = location_path.partition(':')[::2]
base = location2abs_base(locations, location_id)
if base is None:
return None
abs_path = normpath(join(base, path))
return abs_path if abs_path.startswith(base) else None
# =============================================================================
[docs]
def flag_image(theme: str, flag_id: str, active: bool) -> str:
"""Return an URL to an image ON or OFF according to ``active``.
:param str theme:
Current theme.
:param str flag_id:
ID of the flag. For instance, ``'favorite'``.
:param bool active:
State of the flag.
:rtype: str
"""
return '{theme}/cioservice/images/{flag_id}_{active}.png'.format(
theme=theme, flag_id=flag_id, active='on' if active else 'off')