chose extension basing on OS
[platform/upstream/gobject-introspection.git] / giscanner / libtoolimporter.py
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
21 import imp
22 import os
23 import platform
24 import sys
25
26 from .utils import extract_libtool
27
28
29 class LibtoolImporter(object):
30
31     def __init__(self, name, path):
32         self.name = name
33         self.path = path
34
35     @classmethod
36     def find_module(cls, name, packagepath=None):
37         modparts = name.split('.')
38         filename = modparts.pop() + '.la'
39
40         # Given some.package.module 'path' is where subpackages of some.package
41         # should be looked for. See if we can find a ".libs/module.la" relative
42         # to those directories and failing that look for file
43         # "some/package/.libs/module.la" relative to sys.path
44         module = os.path.join(*modparts)
45
46         for path in sys.path:
47             full = os.path.join(path, module, '.libs', filename)
48             if os.path.exists(full):
49                 return cls(name, full)
50
51     def load_module(self, name):
52         realpath = extract_libtool(self.path)
53         platform_system = platform.system()
54
55         if platform_system == 'Darwin':
56             extension = '.dylib'
57         elif platform_system == 'Windows':
58             extension = '.dll'
59         else:
60             extension = '.so'
61
62         mod = imp.load_module(name, open(realpath), realpath, (extension, 'rb', 3))
63         mod.__loader__ = self
64         return mod
65
66     @classmethod
67     def __enter__(cls):
68         sys.meta_path.append(cls)
69
70     @classmethod
71     def __exit__(cls, type, value, traceback):
72         sys.meta_path.remove(cls)