libtoolimporter.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- Mode: Python -*-
  2. # GObject-Introspection - a framework for introspecting GObject libraries
  3. # Copyright (C) 2008 Johan Dahlin
  4. #
  5. # This library is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU Lesser General Public
  7. # License as published by the Free Software Foundation; either
  8. # version 2 of the License, or (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # Lesser General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public
  16. # License along with this library; if not, write to the
  17. # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  18. # Boston, MA 02111-1307, USA.
  19. #
  20. from __future__ import absolute_import
  21. from __future__ import division
  22. from __future__ import print_function
  23. from __future__ import unicode_literals
  24. import imp
  25. import os
  26. import sys
  27. from .utils import extract_libtool
  28. class LibtoolImporter(object):
  29. def __init__(self, name, path):
  30. self.name = name
  31. self.path = path
  32. @classmethod
  33. def find_module(cls, name, packagepath=None):
  34. modparts = name.split('.')
  35. filename = modparts.pop() + '.la'
  36. # Given some.package.module 'path' is where subpackages of some.package
  37. # should be looked for. See if we can find a ".libs/module.la" relative
  38. # to those directories and failing that look for file
  39. # "some/package/.libs/module.la" relative to sys.path
  40. if len(modparts) > 0:
  41. modprefix = os.path.join(*modparts)
  42. modprefix = os.path.join(modprefix, '.libs')
  43. else:
  44. modprefix = '.libs'
  45. for path in sys.path:
  46. full = os.path.join(path, modprefix, filename)
  47. if os.path.exists(full):
  48. return cls(name, full)
  49. def load_module(self, name):
  50. realpath = extract_libtool(self.path)
  51. # The first item of the suffix tuple (which can be, depending on platform,
  52. # one or more valid filename extensions used to name c extension modules)
  53. # is ignored by imp.load_module(). Thus, there is no use in pretending it
  54. # is important and we set it to an empty string.
  55. suffix = ('', 'rb', imp.C_EXTENSION)
  56. mod = imp.load_module(name, open(realpath), realpath, suffix)
  57. mod.__loader__ = self
  58. return mod
  59. @classmethod
  60. def __enter__(cls):
  61. sys.meta_path.append(cls)
  62. @classmethod
  63. def __exit__(cls, exc_type, exc_val, exc_tb):
  64. sys.meta_path.remove(cls)