root / logilab.pylintinstaller / logilab / common / modutils.py

Revision 202:d67e86292521, 18.5 kB (checked in by tziade@…, 11 months ago)

added logilab.pylintinstaller

Line 
1# -*- coding: iso-8859-1 -*-
2# Copyright (c) 2003-2008 LOGILAB S.A. (Paris, FRANCE).
3# http://www.logilab.fr/ -- mailto:contact@logilab.fr
4#
5# This program is free software; you can redistribute it and/or modify it under
6# the terms of the GNU General Public License as published by the Free Software
7# Foundation; either version 2 of the License, or (at your option) any later
8# version.
9#
10# This program is distributed in the hope that it will be useful, but WITHOUT
11# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
13#
14# You should have received a copy of the GNU General Public License along with
15# this program; if not, write to the Free Software Foundation, Inc.,
16# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17"""Python modules manipulation utility functions.
18
19:author:    Logilab
20:copyright: 2003-2008 LOGILAB S.A. (Paris, FRANCE)
21:contact:   http://www.logilab.fr/ -- mailto:python-projects@logilab.org
22
23
24
25:type PY_SOURCE_EXTS: tuple(str)
26:var PY_SOURCE_EXTS: list of possible python source file extension
27
28:type STD_LIB_DIR: str
29:var STD_LIB_DIR: directory where standard modules are located
30
31:type BUILTIN_MODULES: dict
32:var BUILTIN_MODULES: dictionary with builtin module names has key
33"""
34
35__docformat__ = "restructuredtext en"
36
37import sys
38import os
39from os.path import walk, splitext, join, abspath, isdir, dirname, exists
40from imp import find_module, load_module, C_BUILTIN, PY_COMPILED, PKG_DIRECTORY
41
42from logilab.common import STD_BLACKLIST
43
44if sys.platform.startswith('win'):
45    PY_SOURCE_EXTS = ('py', 'pyw')
46    PY_COMPILED_EXTS = ('dll', 'pyd')
47    STD_LIB_DIR = join(sys.prefix, 'lib')
48else:
49    PY_SOURCE_EXTS = ('py',)
50    PY_COMPILED_EXTS = ('so',)
51    STD_LIB_DIR = join(sys.prefix, 'lib', 'python%s' % sys.version[:3])
52   
53BUILTIN_MODULES = dict(zip(sys.builtin_module_names,
54                           [1]*len(sys.builtin_module_names)))
55
56
57class NoSourceFile(Exception):
58    """exception raised when we are not able to get a python
59    source file for a precompiled file
60    """
61
62class LazyObject(object):
63    def __init__(self, module, obj):
64        self.module = module
65        self.obj = obj
66        self._imported = None
67       
68    def __getobj(self):
69        if self._imported is None:
70           self._imported = getattr(load_module_from_name(self.module),
71                                    self.obj)
72        return self._imported
73   
74    def __getattribute__(self, attr):
75        try:
76            return super(LazyObject, self).__getattribute__(attr)
77        except AttributeError, ex:
78            return getattr(self.__getobj(), attr)
79       
80    def __call__(self, *args, **kwargs):
81        return self.__getobj()(*args, **kwargs)
82
83
84def load_module_from_name(dotted_name, path=None, use_sys=1):
85    """load a Python module from it's name
86
87    :type dotted_name: str
88    :param dotted_name: python name of a module or package
89
90    :type path: list or None
91    :param path:
92      optional list of path where the module or package should be
93      searched (use sys.path if nothing or None is given)
94
95    :type use_sys: bool
96    :param use_sys:
97      boolean indicating whether the sys.modules dictionary should be
98      used or not
99
100
101    :raise ImportError: if the module or package is not found
102   
103    :rtype: module
104    :return: the loaded module
105    """
106    return load_module_from_modpath(dotted_name.split('.'), path, use_sys)
107
108
109def load_module_from_modpath(parts, path=None, use_sys=1):
110    """load a python module from it's splitted name
111
112    :type parts: list(str) or tuple(str)
113    :param parts:
114      python name of a module or package splitted on '.'
115
116    :type path: list or None
117    :param path:
118      optional list of path where the module or package should be
119      searched (use sys.path if nothing or None is given)
120
121    :type use_sys: bool
122    :param use_sys:
123      boolean indicating whether the sys.modules dictionary should be used or not
124
125    :param _prefix: used internally, should not be specified
126
127
128    :raise ImportError: if the module or package is not found
129   
130    :rtype: module
131    :return: the loaded module
132    """
133    if use_sys:
134        try:
135            return sys.modules['.'.join(parts)]
136        except KeyError:
137            pass
138    modpath = []
139    prevmodule = None
140    for part in parts:
141        modpath.append(part)
142        curname = ".".join(modpath)
143        module = None
144        if len(modpath) != len(parts):
145            # even with use_sys=False, should try to get outer packages from sys.modules
146            module = sys.modules.get(curname)
147        if module is None:
148            mp_file, mp_filename, mp_desc = find_module(part, path)
149            module = load_module(curname, mp_file, mp_filename, mp_desc)
150        if prevmodule:
151            setattr(prevmodule, part, module)
152        _file = getattr(module, "__file__", "")
153        if not _file and len(modpath) != len(parts):
154            raise ImportError("no module in %s" % ".".join(parts[len(modpath):]) )
155        path = [dirname( _file )]
156        prevmodule = module
157    return module
158
159
160def load_module_from_file(filepath, path=None, use_sys=1):
161    """load a Python module from it's path
162
163    :type filepath: str
164    :param dotted_name: path to the python module or package
165
166    :type path: list or None
167    :param path:
168      optional list of path where the module or package should be
169      searched (use sys.path if nothing or None is given)
170
171    :type use_sys: bool
172    :param use_sys:
173      boolean indicating whether the sys.modules dictionary should be
174      used or not
175
176
177    :raise ImportError: if the module or package is not found
178   
179    :rtype: module
180    :return: the loaded module
181    """
182    return load_module_from_modpath(modpath_from_file(filepath), path, use_sys)
183
184
185def modpath_from_file(filename):
186    """given a file path return the corresponding splitted module's name
187    (i.e name of a module or package splitted on '.')
188
189    :type filename: str
190    :param filename: file's path for which we want the module's name
191
192
193    :raise ImportError:
194      if the corresponding module's name has not been found
195
196    :rtype: list(str)
197    :return: the corresponding splitted module's name
198    """
199    base = splitext(abspath(filename))[0]
200    for path in sys.path:
201        path = abspath(path)
202        if path and base[:len(path)] == path:
203            if filename.find('site-packages') != -1 and \
204                   path.find('site-packages') == -1:
205                continue
206            mod_path = [module for module in base[len(path):].split(os.sep)
207                        if module]
208            for part in mod_path[:-1]:
209                path = join(path, part)
210                if not _has_init(path):
211                    break
212            else:
213                break
214    else:
215        raise ImportError('Unable to find module for %s in %s' % (
216            filename, ', \n'.join(sys.path)))
217    return mod_path
218
219
220
221def file_from_modpath(modpath, path=None, context_file=None):
222    """given a mod path (ie splited module / package name), return the
223    corresponding file, giving priority to source file over precompiled
224    file if it exists
225
226    :type modpath: list or tuple
227    :param modpath:
228      splitted module's name (i.e name of a module or package splitted
229      on '.')
230      (this means explicit relative imports that start with dots have
231      empty strings in this list!)
232
233    :type path: list or None
234    :param path:
235      optional list of path where the module or package should be
236      searched (use sys.path if nothing or None is given)
237
238    :type context_file: str or None
239    :param context_file:
240      context file to consider, necessary if the identifier has been
241      introduced using a relative import unresolvable in the actual
242      context (i.e. modutils)
243     
244    :raise ImportError: if there is no such module in the directory
245
246    :rtype: str or None
247    :return:
248      the path to the module's file or None if it's an integrated
249      builtin module such as 'sys'
250    """
251    if context_file is not None:
252        context = dirname(context_file)
253    else:
254        context = context_file
255    if modpath[0] == 'xml':
256        # handle _xmlplus
257        try:
258            return _file_from_modpath(['_xmlplus'] + modpath[1:], path, context)
259        except ImportError:
260            return _file_from_modpath(modpath, path, context)
261    elif modpath == ['os', 'path']:
262        # FIXME: currently ignoring search_path...
263        return os.path.__file__
264    return _file_from_modpath(modpath, path, context)
265
266
267   
268def get_module_part(dotted_name, context_file=None):
269    """given a dotted name return the module part of the name :
270   
271    >>> get_module_part('logilab.common.modutils.get_module_part')
272    'logilab.common.modutils'
273
274   
275    :type dotted_name: str
276    :param dotted_name: full name of the identifier we are interested in
277
278    :type context_file: str or None
279    :param context_file:
280      context file to consider, necessary if the identifier has been
281      introduced using a relative import unresolvable in the actual
282      context (i.e. modutils)
283
284   
285    :raise ImportError: if there is no such module in the directory
286   
287    :rtype: str or None
288    :return:
289      the module part of the name or None if we have not been able at
290      all to import the given name
291
292    XXX: deprecated, since it doesn't handle package precedence over module
293    (see #10066)
294    """
295    # os.path trick
296    if dotted_name.startswith('os.path'):
297        return 'os.path'
298    parts = dotted_name.split('.')
299    if context_file is not None:
300        # first check for builtin module which won't be considered latter
301        # in that case (path != None)
302        if parts[0] in BUILTIN_MODULES:
303            if len(parts) > 2:
304                raise ImportError(dotted_name)
305            return parts[0]
306        # don't use += or insert, we want a new list to be created !
307    path = None
308    starti = 0
309    if parts[0] == '':
310        assert context_file is not None, \
311                'explicit relative import, but no context_file?'
312        path = [] # prevent resolving the import non-relatively
313        starti = 1
314    while parts[starti] == '': # for all further dots: change context
315        starti += 1
316        context_file = dirname(context_file)
317    for i in range(starti, len(parts)):
318        try:
319            file_from_modpath(parts[starti:i+1],
320                    path=path, context_file=context_file)
321        except ImportError:
322            if not i >= max(1, len(parts) - 2):
323                raise
324            return '.'.join(parts[:i])
325    return dotted_name
326
327
328   
329def get_modules(package, src_directory, blacklist=STD_BLACKLIST):
330    """given a package directory return a list of all available python
331    modules in the package and its subpackages
332
333    :type package: str
334    :param package: the python name for the package
335
336    :type src_directory: str
337    :param src_directory:
338      path of the directory corresponding to the package
339
340    :type blacklist: list or tuple
341    :param blacklist:
342      optional list of files or directory to ignore, default to
343      the value of `logilab.common.STD_BLACKLIST`
344
345    :rtype: list
346    :return:
347      the list of all available python modules in the package and its
348      subpackages
349    """
350    def func(modules, directory, fnames):
351        """walk handler"""
352        # remove files/directories in the black list
353        for norecurs in blacklist:
354            try:
355                fnames.remove(norecurs)
356            except ValueError:
357                continue
358        # check for __init__.py
359        if not '__init__.py' in fnames:
360            while fnames:
361                fnames.pop()
362        elif directory != src_directory:
363            #src = join(directory, file)
364            dir_package = directory[len(src_directory):].replace(os.sep, '.')
365            modules.append(package + dir_package)
366        for filename in fnames:
367            src = join(directory, filename)
368            if isdir(src):
369                continue
370            if _is_python_file(filename) and filename != '__init__.py':
371                module = package + src[len(src_directory):-3]
372                modules.append(module.replace(os.sep, '.'))
373    modules = []
374    walk(src_directory, func, modules)
375    return modules
376
377
378
379def get_module_files(src_directory, blacklist=STD_BLACKLIST):
380    """given a package directory return a list of all available python
381    module's files in the package and its subpackages
382
383    :type src_directory: str
384    :param src_directory:
385      path of the directory corresponding to the package
386
387    :type blacklist: list or tuple
388    :param blacklist:
389      optional list of files or directory to ignore, default to the value of
390      `logilab.common.STD_BLACKLIST`
391
392    :rtype: list
393    :return:
394      the list of all available python module's files in the package and
395      its subpackages
396    """
397    def func(files, directory, fnames):
398        """walk handler"""
399        # remove files/directories in the black list
400        for norecurs in blacklist:
401            try:
402                fnames.remove(norecurs)
403            except ValueError:
404                continue
405        # check for __init__.py
406        if not '__init__.py' in fnames:
407            while fnames:
408                fnames.pop()           
409        for filename in fnames:
410            src = join(directory, filename)
411            if isdir(src):
412                continue
413            if _is_python_file(filename):
414                files.append(src)
415    files = []
416    walk(src_directory, func, files)
417    return files
418
419
420def get_source_file(filename, include_no_ext=False):
421    """given a python module's file name return the matching source file
422    name (the filename will be returned identically if it's a already an
423    absolute path to a python source file...)
424
425    :type filename: str
426    :param filename: python module's file name
427
428
429    :raise NoSourceFile: if no source file exists on the file system
430   
431    :rtype: str
432    :return: the absolute path of the source file if it exists
433    """
434    base, orig_ext = splitext(abspath(filename))
435    for ext in PY_SOURCE_EXTS:
436        source_path = '%s.%s' % (base, ext)
437        if exists(source_path):
438            return source_path
439    if include_no_ext and not orig_ext and exists(base):
440        return base
441    raise NoSourceFile(filename)
442
443
444
445def is_python_source(filename):
446    """
447    rtype: bool
448    return: True if the filename is a python source file
449    """
450    return splitext(filename)[1][1:] in PY_SOURCE_EXTS
451
452
453   
454def is_standard_module(modname, std_path=(STD_LIB_DIR,)):
455    """try to guess if a module is a standard python module (by default,
456    see `std_path` parameter's description)
457   
458    :type modname: str
459    :param modname: name of the module we are interested in
460
461    :type std_path: list(str) or tuple(str)
462    :param std_path: list of path considered has standard
463
464
465    :rtype: bool
466    :return:
467      true if the module:
468      - is located on the path listed in one of the directory in `std_path`
469      - is a built-in module
470    """
471    modpath = modname.split('.')
472    modname = modpath[0]
473    try:
474        filename = file_from_modpath(modpath)
475    except ImportError:
476        # import failed, i'm probably not so wrong by supposing it's
477        # not standard...
478        return 0
479    # modules which are not living in a file are considered standard
480    # (sys and __builtin__ for instance)
481    if filename is None:
482        return 1
483    filename = abspath(filename)
484    for path in std_path:
485        path = abspath(path)
486        if filename.startswith(path):
487            pfx_len = len(path)
488            if filename[pfx_len+1:pfx_len+14] != 'site-packages':
489                return 1
490            return 0
491    return False
492
493   
494
495def is_relative(modname, from_file):
496    """return true if the given module name is relative to the given
497    file name
498   
499    :type modname: str
500    :param modname: name of the module we are interested in
501
502    :type from_file: str
503    :param from_file:
504      path of the module from which modname has been imported
505   
506    :rtype: bool
507    :return:
508      true if the module has been imported relativly to `from_file`
509    """
510    if not isdir(from_file):
511        from_file = dirname(from_file)
512    if from_file in sys.path:
513        return False
514    try:
515        find_module(modname.split('.')[0], [from_file])
516        return True
517    except ImportError:
518        return False
519
520
521# internal only functions #####################################################
522
523def _file_from_modpath(modpath, path=None, context=None):
524    """given a mod path (ie splited module / package name), return the
525    corresponding file
526
527    this function is used internally, see `file_from_modpath`'s
528    documentation for more information
529    """
530    assert len(modpath) > 0
531    if context is not None:
532        try:
533            mtype, mp_filename = _module_file(modpath, [context])
534        except ImportError:
535            mtype, mp_filename = _module_file(modpath, path)
536    else:
537        mtype, mp_filename = _module_file(modpath, path)
538    if mtype == PY_COMPILED:
539        try:
540            return get_source_file(mp_filename)
541        except NoSourceFile:
542            return mp_filename
543    elif mtype == C_BUILTIN:
544        # integrated builtin module
545        return None
546    elif mtype == PKG_DIRECTORY:
547        mp_filename = _has_init(mp_filename)
548    return mp_filename
549