1 #!/usr/bin/env python 2 3 """ 4 Import utilities. 5 6 Copyright (C) 2017, 2018 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from os.path import isdir, join, split, splitext 23 from os import listdir 24 from importlib import import_module 25 26 reserved = ["__init__", "common", "manifest"] 27 28 def get_extensions(dirname, modname, stores, reserved, prefix=None): 29 30 "Import extensions inside 'dirname'." 31 32 for filename in listdir(dirname): 33 pathname = join(dirname, filename) 34 35 # Descend into directories, prefixing the identified modules. 36 37 if isdir(pathname): 38 store_name = prefix and "%s.%s" % (prefix, modname) or filename 39 get_extensions(pathname, "%s.%s" % (modname, filename), 40 stores, reserved, store_name) 41 continue 42 43 # Identify modules and import them. 44 45 leafname, ext = splitext(filename) 46 47 if ext == ".py" and leafname not in reserved: 48 store_name = prefix and "%s.%s" % (prefix, leafname) or leafname 49 stores[store_name] = import_module("%s.%s" % (modname, leafname)) 50 51 def get_mapping(modules, get_key, get_value): 52 53 """ 54 Using the 'modules' mapping, employ 'get_key' and 'get_value' to register 55 objects provided by the modules in a mapping. 56 """ 57 58 mapping = {} 59 60 # Use the callables to obtain the keys and values from modules. 61 62 for name, module in modules.items(): 63 mapping[get_key(name, module)] = get_value(module) 64 65 return mapping 66 67 def get_modules(module_file, module_name): 68 69 """ 70 Obtain details of the indicated module's package using 'module_file', 71 corresponding to a __file__ attribute, and 'module_name', corresponding to 72 a __name__ attribute. 73 """ 74 75 dirname = split(module_file)[0] 76 package = module_name.rsplit(".", 1)[0] 77 78 # Define an attribute mapping names to modules. 79 80 modules = {} 81 get_extensions(dirname, package, modules, reserved) 82 return modules 83 84 # vim: tabstop=4 expandtab shiftwidth=4