1# Copyright (c) 2022 Nordic Semiconductor ASA
2#
3# SPDX-License-Identifier: Apache-2.0
4
5import importlib
6import logging
7import os
8from pathlib import Path
9
10from fetchers.core import ZephyrBlobFetcher
11
12_logger = logging.getLogger('fetchers')
13
14def _import_fetcher_module(fetcher_name):
15    try:
16        importlib.import_module(f'fetchers.{fetcher_name}')
17    except ImportError as ie:
18        # Fetchers are supposed to gracefully handle failures when they
19        # import anything outside of stdlib, but they sometimes do
20        # not. Catch ImportError to handle this.
21        _logger.warning(f'The module for fetcher "{fetcher_name}" '
22                        f'could not be imported ({ie}). This most likely '
23                        'means it is not handling its dependencies properly. '
24                        'Please report this to the zephyr developers.')
25
26# We import these here to ensure the BlobFetcher subclasses are
27# defined; otherwise, BlobFetcher.get_fetchers() won't work.
28
29# Those do not contain subclasses of ZephyrBlobFetcher
30name_blocklist = ['__init__', 'core']
31
32fetchers_dir = Path(__file__).parent.resolve()
33for f in [f for f in os.listdir(fetchers_dir)]:
34    file = fetchers_dir / Path(f)
35    if file.suffix == '.py' and file.stem not in name_blocklist:
36        _import_fetcher_module(file.stem)
37
38def get_fetcher_cls(scheme):
39    '''Get a fetcher's class object, given a scheme.'''
40    for cls in ZephyrBlobFetcher.get_fetchers():
41        if scheme in cls.schemes():
42            return cls
43    raise ValueError('unknown fetcher for scheme "{}"'.format(scheme))
44
45__all__ = ['ZephyrBlobFetcher', 'get_fetcher_cls']
46