plugins.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''Plugins helpers for Qubes
  24. Qubes uses two types of plugins: virtual machines and extensions.
  25. '''
  26. import imp
  27. import os
  28. class Plugin(type):
  29. '''Base metaclass for plugins'''
  30. def __init__(cls, name, bases, dict_):
  31. # pylint: disable=unused-argument
  32. if hasattr(cls, 'register'):
  33. cls.register[cls.__name__] = cls
  34. else:
  35. # we've got root class
  36. cls.register = {}
  37. def __getitem__(cls, name):
  38. return cls.register[name]
  39. def load(modfile):
  40. '''Load (import) all plugins from subpackage.
  41. This function should be invoked from ``__init__.py`` in a package like that:
  42. >>> __all__ = qubes.plugins.load(__file__) # doctest: +SKIP
  43. '''
  44. path = os.path.dirname(modfile)
  45. listdir = os.listdir(path)
  46. ret = set()
  47. # pylint: disable=unused-variable
  48. for suffix, mode, type_ in imp.get_suffixes():
  49. for filename in listdir:
  50. if filename.endswith(suffix):
  51. ret.add(filename[:-len(suffix)])
  52. if '__init__' in ret:
  53. ret.remove('__init__')
  54. return list(sorted(ret))