1# Copyright 2013 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5"""Module scan and load system. 6 7The main interface to this module is the Scan function, which triggers a 8recursive scan of all packages and modules below cr, with modules being 9imported as they are found. 10This allows all the plugins in the system to self register. 11The aim is to make writing plugins as simple as possible, minimizing the 12boilerplate so the actual functionality is clearer. 13""" 14from importlib import import_module 15import os 16import sys 17 18import cr 19 20# This is the name of the variable inserted into modules to track which 21# scanners have been applied. 22_MODULE_SCANNED_TAG = '_CR_MODULE_SCANNED' 23 24 25class AutoExport(object): 26 """A marker for classes that should be promoted up into the cr namespace.""" 27 28 29def _AutoExportScanner(module): 30 """Scan the modules for things that need wiring up automatically.""" 31 for name, value in module.__dict__.items(): 32 if isinstance(value, type) and issubclass(value, AutoExport): 33 # Add this straight to the cr module. 34 if not hasattr(cr, name): 35 setattr(cr, name, value) 36 37 38scan_hooks = [_AutoExportScanner] 39 40 41def _Import(name): 42 """Import a module or package if it is not already imported.""" 43 module = sys.modules.get(name, None) 44 if module is not None: 45 return module 46 return import_module(name, None) 47 48 49def _ScanModule(module): 50 """Runs all the scan_hooks for a module.""" 51 scanner_tags = getattr(module, _MODULE_SCANNED_TAG, None) 52 if scanner_tags is None: 53 # First scan, add the scanned marker set. 54 scanner_tags = set() 55 setattr(module, _MODULE_SCANNED_TAG, scanner_tags) 56 for scan in scan_hooks: 57 if scan not in scanner_tags: 58 scanner_tags.add(scan) 59 scan(module) 60 61 62def _ScanPackage(package): 63 """Scan a package for child packages and modules.""" 64 modules = [] 65 # Recurse sub folders. 66 for path in package.__path__: 67 try: 68 basenames = sorted(os.listdir(path)) 69 except OSError: 70 basenames = [] 71 packages = [] 72 for basename in basenames: 73 fullpath = os.path.join(path, basename) 74 if os.path.isdir(fullpath): 75 name = '.'.join([package.__name__, basename]) 76 packages.append(name) 77 elif basename.endswith('.py') and not basename.startswith('_'): 78 name = '.'.join([package.__name__, basename[:-3]]) 79 module = _Import(name) 80 _ScanModule(module) 81 modules.append(module) 82 for name in packages: 83 child = _Import(name) 84 modules.extend(_ScanPackage(child)) 85 return modules 86 87 88def Import(package, name): 89 module = _Import(package + '.' + name) 90 path = getattr(module, '__path__', None) 91 if path: 92 _ScanPackage(module) 93 else: 94 _ScanModule(module) 95 return module 96 97 98def Scan(): 99 """Scans from the cr package down, loading modules as needed. 100 101 This finds all packages and modules below the cr package, by scanning the 102 file system. It imports all the packages, and then runs post import hooks on 103 each module to do any automated work. One example of this is the hook that 104 finds all classes that extend AutoExport and copies them up into the cr 105 namespace directly. 106 107 Modules are allowed to refer to each other, their import will be retried 108 until it succeeds or no progress can be made on any module. 109 """ 110 modules = _ScanPackage(cr) 111 # Now scan all the found modules one more time. 112 # This happens after all imports, in case any imports register scan hooks. 113 for module in modules: 114 _ScanModule(module) 115