|
| 1 | +# This program is free software: you can redistribute it and/or modify it under the |
| 2 | +# terms of the Apache License (v2.0) as published by the Apache Software Foundation. |
| 3 | +# |
| 4 | +# This program is distributed in the hope that it will be useful, but WITHOUT ANY |
| 5 | +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
| 6 | +# PARTICULAR PURPOSE. See the Apache License for more details. |
| 7 | +# |
| 8 | +# You should have received a copy of the Apache License along with this program. |
| 9 | +# If not, see <https://www.apache.org/licenses/LICENSE-2.0>. |
| 10 | + |
| 11 | +"""Assets/templates required by StreamKit.""" |
| 12 | + |
| 13 | +# type annotations |
| 14 | +from typing import List, Dict, IO, Union, Generator |
| 15 | + |
| 16 | +# standard libs |
| 17 | +import os |
| 18 | +import re |
| 19 | +import fnmatch |
| 20 | +import functools |
| 21 | + |
| 22 | +# internal libs |
| 23 | +from ..core.logging import Logger |
| 24 | + |
| 25 | + |
| 26 | +# module level logger |
| 27 | +log = Logger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +# either bytes or str depending on how the file was opened |
| 31 | +FileData = Union[str, bytes] |
| 32 | + |
| 33 | + |
| 34 | +# The absolute location of this directory. |
| 35 | +# The trailing path separator is necessary for reconstituting relative paths. |
| 36 | +DIRECTORY = os.path.dirname(__file__) + os.path.sep |
| 37 | + |
| 38 | + |
| 39 | +def abspath(relative_path: str) -> str: |
| 40 | + """Construct the absolute path to the file within /assets.""" |
| 41 | + path = relative_path.lstrip(os.path.sep) |
| 42 | + return os.path.normpath(os.path.join(DIRECTORY, path)) |
| 43 | + |
| 44 | + |
| 45 | +# do not yield non-asset paths |
| 46 | +IGNORE_PATHS = r'.*\/(__init__.py$|__pycache__\/.*)' |
| 47 | + |
| 48 | + |
| 49 | +def _iter_paths() -> Generator[str, None, None]: |
| 50 | + """Yield relative file paths below /assets""" |
| 51 | + ignore = re.compile(IGNORE_PATHS) |
| 52 | + for root, dirs, files in os.walk(DIRECTORY): |
| 53 | + yield from filter(lambda path: ignore.match(path) is None, |
| 54 | + map(functools.partial(os.path.join, root), files)) |
| 55 | + |
| 56 | + |
| 57 | +def _match_glob(pattern: str, path: str) -> bool: |
| 58 | + """True if `path` matches `pattern`.""" |
| 59 | + return fnmatch.fnmatch(path, pattern) |
| 60 | + |
| 61 | + |
| 62 | +def _match_regex(pattern: str, path: str) -> bool: |
| 63 | + """True if `path` matches `pattern`.""" |
| 64 | + return re.match(pattern, path) is not None |
| 65 | + |
| 66 | + |
| 67 | +def find_files(pattern: str, regex: bool = False, relative: bool = True) -> List[str]: |
| 68 | + """List the assets matching a glob/regex `pattern`.""" |
| 69 | + pattern = pattern.lstrip(os.path.sep) |
| 70 | + paths = sorted(filter(functools.partial(_match_glob if not regex else _match_regex, pattern), |
| 71 | + map(lambda path: os.path.normpath(path).replace(DIRECTORY, ''), _iter_paths()))) |
| 72 | + if relative: |
| 73 | + return paths |
| 74 | + else: |
| 75 | + return list(map(abspath, paths)) |
| 76 | + |
| 77 | + |
| 78 | +def open_asset(relative_path: str, mode: str = 'r', **kwargs) -> IO: |
| 79 | + """ |
| 80 | + Open a file from the /assets subpackage. |
| 81 | +
|
| 82 | + Parameters: |
| 83 | + relative_path (str): |
| 84 | + The relative file path below /assets directory. |
| 85 | + mode (str): |
| 86 | + The mode to open the file with (default: 'r'). |
| 87 | + **kwargs: |
| 88 | + Additional keyword arguments are passed to open. |
| 89 | +
|
| 90 | + Returns: |
| 91 | + file: IO |
| 92 | + The file descriptor for the open file asset. |
| 93 | + """ |
| 94 | + dirname = os.path.dirname(__file__) |
| 95 | + filepath = os.path.join(dirname, relative_path) |
| 96 | + try: |
| 97 | + return open(filepath, mode=mode, **kwargs) |
| 98 | + except FileNotFoundError: |
| 99 | + log.error(f'missing {relative_path}') |
| 100 | + raise |
| 101 | + |
| 102 | + |
| 103 | +@functools.lru_cache(maxsize=None) |
| 104 | +def load_asset(relative_path: str, mode: str = 'r', **kwargs) -> FileData: |
| 105 | + """ |
| 106 | + Load an asset from its `relative_path` below /assets. |
| 107 | +
|
| 108 | + Parameters: |
| 109 | + relative_path (str): |
| 110 | + The relative file path below /assets directory. |
| 111 | + mode (str): |
| 112 | + The mode to open the file with (default: 'r'). |
| 113 | + **kwargs: |
| 114 | + Additional keyword arguments are passed to open. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + content: Union[str, bytes] |
| 118 | + The content of the file (depends on the mode). |
| 119 | + """ |
| 120 | + with open_asset(relative_path, mode=mode, **kwargs) as source: |
| 121 | + content = source.read() |
| 122 | + log.debug(f'loaded /assets/{relative_path}') |
| 123 | + return content |
| 124 | + |
| 125 | + |
| 126 | +def load_assets(pattern: str, regex: bool = False, **kwargs) -> Dict[str, FileData]: |
| 127 | + """ |
| 128 | + Load all files matching `pattern`. |
| 129 | +
|
| 130 | + Parameters: |
| 131 | + pattern (str): |
| 132 | + Either a glob pattern or regular expression for the files to include. |
| 133 | + regex (bool): |
| 134 | + Whether to interpret the `pattern` as a regular expression (default: False). |
| 135 | +
|
| 136 | + Returns: |
| 137 | + file_data: Dict[str, Union[str, bytes]] |
| 138 | + A dictionary of the file data, indexed by the relative file path within |
| 139 | + the /assets directory. Use `mode='rb'` to return raw bytes data. |
| 140 | + """ |
| 141 | + return {path: load_asset(path, **kwargs) for path in find_files(pattern, regex=regex)} |
0 commit comments