Initial import
[mycode.git] / pys60 / pyrepl / pyrepl / module_lister.py
blob192a24a6baa24a6be87c7e96de1c62faef3c2b3c
1 # Copyright 2000-2004 Michael Hudson mwh@python.net
3 # All Rights Reserved
6 # Permission to use, copy, modify, and distribute this software and
7 # its documentation for any purpose is hereby granted without fee,
8 # provided that the above copyright notice appear in all copies and
9 # that both that copyright notice and this permission notice appear in
10 # supporting documentation.
12 # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
13 # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14 # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
15 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
16 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
17 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
18 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 from pyrepl.completing_reader import uniqify
21 import os, sys
23 # for the completion support.
24 # this is all quite nastily written.
25 _packages = {}
27 def _make_module_list_dir(dir, suffs, prefix=''):
28 l = []
29 for fname in os.listdir(dir):
30 file = os.path.join(dir, fname)
31 if os.path.isfile(file):
32 for suff in suffs:
33 if fname.endswith(suff):
34 l.append( prefix + fname[:-len(suff)] )
35 break
36 elif os.path.isdir(file) \
37 and os.path.exists(os.path.join(file, "__init__.py")):
38 l.append( prefix + fname )
39 _packages[prefix + fname] = _make_module_list_dir(
40 file, suffs, prefix + fname + '.' )
41 l = uniqify(l)
42 l.sort()
43 return l
45 def _make_module_list():
46 import imp
47 suffs = [x[0] for x in imp.get_suffixes() if x[0] != '.pyc']
48 def compare(x, y):
49 c = -cmp(len(x), len(y))
50 if c:
51 return c
52 else:
53 return -cmp(x, y)
54 suffs.sort(compare)
55 _packages[''] = list(sys.builtin_module_names)
56 for dir in sys.path:
57 if dir == '':
58 dir = '.'
59 if os.path.isdir(dir):
60 _packages[''] += _make_module_list_dir(dir, suffs)
61 _packages[''].sort()
63 def find_modules(stem):
64 l = stem.split('.')
65 pack = '.'.join(l[:-1])
66 try:
67 mods = _packages[pack]
68 except KeyError:
69 raise ImportError, "can't find \"%s\" package"%pack
70 return [mod for mod in mods if mod.startswith(stem)]