plugins.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/python2 -O
  2. # -*- coding: utf-8 -*-
  3. '''Plugins helpers for Qubes
  4. Qubes uses two types of plugins: virtual machines and extensions.
  5. '''
  6. import imp
  7. import inspect
  8. import os
  9. import sys
  10. class Plugin(type):
  11. '''Base metaclass for plugins'''
  12. def __init__(cls, name, bases, dict_):
  13. if hasattr(cls, 'register'):
  14. cls.register[cls.__name__] = cls
  15. else:
  16. # we've got root class
  17. cls.register = {}
  18. def __getitem__(cls, name):
  19. return cls.register[name]
  20. def load(modfile):
  21. '''Load (import) all plugins from subpackage.
  22. This function should be invoked from ``__init__.py`` in a package like that:
  23. >>> __all__ = qubes.plugins.load(__file__) # doctest: +SKIP
  24. '''
  25. path = os.path.dirname(modfile)
  26. listdir = os.listdir(path)
  27. ret = set()
  28. for suffix, mode, type_ in imp.get_suffixes():
  29. for filename in listdir:
  30. if filename.endswith(suffix):
  31. ret.add(filename[:-len(suffix)])
  32. if '__init__' in ret:
  33. ret.remove('__init__')
  34. return list(sorted(ret))