comparison env/lib/python3.9/site-packages/argcomplete/_check_module.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 """
2 Utility for locating a module (or package's __main__.py) with a given name
3 and verifying it contains the PYTHON_ARGCOMPLETE_OK marker.
4
5 The module name should be specified in a form usable with `python -m`.
6
7 Intended to be invoked by argcomplete's global completion function.
8 """
9 import os
10 import sys
11 import tokenize
12
13 try:
14 from importlib.util import find_spec
15 except ImportError:
16 from collections import namedtuple
17 from imp import find_module
18
19 ModuleSpec = namedtuple(
20 'ModuleSpec', ['origin', 'has_location', 'submodule_search_locations'])
21
22 def find_spec(name):
23 """Minimal implementation as required by `find`."""
24 try:
25 f, path, _ = find_module(name)
26 except ImportError:
27 return None
28 has_location = path is not None
29 if f is None:
30 return ModuleSpec(None, has_location, [path])
31 f.close()
32 return ModuleSpec(path, has_location, None)
33
34
35 class ArgcompleteMarkerNotFound(RuntimeError):
36 pass
37
38
39 def find(name, return_package=False):
40 names = name.split('.')
41 spec = find_spec(names[0])
42 if spec is None:
43 raise ArgcompleteMarkerNotFound(
44 'no module named "{}"'.format(names[0]))
45 if not spec.has_location:
46 raise ArgcompleteMarkerNotFound('cannot locate file')
47 if spec.submodule_search_locations is None:
48 if len(names) != 1:
49 raise ArgcompleteMarkerNotFound(
50 '{} is not a package'.format(names[0]))
51 return spec.origin
52 if len(spec.submodule_search_locations) != 1:
53 raise ArgcompleteMarkerNotFound('expecting one search location')
54 path = os.path.join(spec.submodule_search_locations[0], *names[1:])
55 if os.path.isdir(path):
56 filename = '__main__.py'
57 if return_package:
58 filename = '__init__.py'
59 return os.path.join(path, filename)
60 else:
61 return path + '.py'
62
63
64 def main():
65 try:
66 name = sys.argv[1]
67 except IndexError:
68 raise ArgcompleteMarkerNotFound('missing argument on the command line')
69
70 filename = find(name)
71 if hasattr(tokenize, 'open'):
72 open_func = tokenize.open
73 else:
74 open_func = open
75
76 try:
77 fp = open_func(filename)
78 except OSError:
79 raise ArgcompleteMarkerNotFound('cannot open file')
80
81 with fp:
82 head = fp.read(1024)
83
84 if 'PYTHON_ARGCOMPLETE_OK' not in head:
85 raise ArgcompleteMarkerNotFound('marker not found')
86
87
88 if __name__ == '__main__':
89 try:
90 main()
91 except ArgcompleteMarkerNotFound as e:
92 sys.exit(e)