in builder/core/scripts.py [0:0]
def load(path='.'):
""" Loads all scripts from ${path}/.builder/**/*.py to make their classes available """
if len(Scripts.all_classes) == 0:
Scripts.all_classes = _get_all_dynamic_classes()
# Load any classes from path
path = os.path.abspath(os.path.join(path, '.builder'))
if os.path.isdir(path):
print('Loading scripts from {}'.format(path))
scripts = glob.glob(os.path.join(path, '*.py'))
scripts += glob.glob(os.path.join(path, '**', '*.py'))
for script in scripts:
if not script.endswith('.py'):
continue
# Ensure that the import path includes the directory the script is in
# so that relative imports work
script_dir = os.path.dirname(script)
if script_dir not in sys.path:
sys.path.append(script_dir)
print("Importing {}".format(os.path.abspath(script)), flush=True)
name = os.path.split(script)[1].split('.')[0]
spec = importlib.util.spec_from_file_location(name, script)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Must invalidate caches or sometimes the loaded classes won't be found
# See: https://docs.python.org/3/library/importlib.html#importlib.invalidate_caches
importlib.invalidate_caches()
# Report newly loaded classes
classes = frozenset(_get_all_dynamic_classes())
new_classes = classes.difference(Scripts.all_classes)
if new_classes:
print("Imported {}".format(
', '.join([c.__name__ for c in new_classes])))
Scripts.all_classes.update(new_classes)