eric6/DebugClients/Python/coverage/python.py

changeset 6942
2602857055c5
parent 6649
f1b3a73831c9
child 7427
362cd1b6f81a
equal deleted inserted replaced
6941:f99d60d6b59b 6942:2602857055c5
1 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
3
4 """Python source expertise for coverage.py"""
5
6 import os.path
7 import types
8 import zipimport
9
10 from coverage import env, files
11 from coverage.misc import contract, expensive, isolate_module, join_regex
12 from coverage.misc import CoverageException, NoSource
13 from coverage.parser import PythonParser
14 from coverage.phystokens import source_token_lines, source_encoding
15 from coverage.plugin import FileReporter
16
17 os = isolate_module(os)
18
19
20 @contract(returns='bytes')
21 def read_python_source(filename):
22 """Read the Python source text from `filename`.
23
24 Returns bytes.
25
26 """
27 with open(filename, "rb") as f:
28 source = f.read()
29
30 if env.IRONPYTHON:
31 # IronPython reads Unicode strings even for "rb" files.
32 source = bytes(source)
33
34 return source.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
35
36
37 @contract(returns='unicode')
38 def get_python_source(filename):
39 """Return the source code, as unicode."""
40 base, ext = os.path.splitext(filename)
41 if ext == ".py" and env.WINDOWS:
42 exts = [".py", ".pyw"]
43 else:
44 exts = [ext]
45
46 for ext in exts:
47 try_filename = base + ext
48 if os.path.exists(try_filename):
49 # A regular text file: open it.
50 source = read_python_source(try_filename)
51 break
52
53 # Maybe it's in a zip file?
54 source = get_zip_bytes(try_filename)
55 if source is not None:
56 break
57 else:
58 # Couldn't find source.
59 exc_msg = "No source for code: '%s'.\n" % (filename,)
60 exc_msg += "Aborting report output, consider using -i."
61 raise NoSource(exc_msg)
62
63 # Replace \f because of http://bugs.python.org/issue19035
64 source = source.replace(b'\f', b' ')
65 source = source.decode(source_encoding(source), "replace")
66
67 # Python code should always end with a line with a newline.
68 if source and source[-1] != '\n':
69 source += '\n'
70
71 return source
72
73
74 @contract(returns='bytes|None')
75 def get_zip_bytes(filename):
76 """Get data from `filename` if it is a zip file path.
77
78 Returns the bytestring data read from the zip file, or None if no zip file
79 could be found or `filename` isn't in it. The data returned will be
80 an empty string if the file is empty.
81
82 """
83 markers = ['.zip'+os.sep, '.egg'+os.sep, '.pex'+os.sep]
84 for marker in markers:
85 if marker in filename:
86 parts = filename.split(marker)
87 try:
88 zi = zipimport.zipimporter(parts[0]+marker[:-1])
89 except zipimport.ZipImportError:
90 continue
91 try:
92 data = zi.get_data(parts[1])
93 except IOError:
94 continue
95 return data
96 return None
97
98
99 def source_for_file(filename):
100 """Return the source file for `filename`.
101
102 Given a file name being traced, return the best guess as to the source
103 file to attribute it to.
104
105 """
106 if filename.endswith(".py"):
107 # .py files are themselves source files.
108 return filename
109
110 elif filename.endswith((".pyc", ".pyo")):
111 # Bytecode files probably have source files near them.
112 py_filename = filename[:-1]
113 if os.path.exists(py_filename):
114 # Found a .py file, use that.
115 return py_filename
116 if env.WINDOWS:
117 # On Windows, it could be a .pyw file.
118 pyw_filename = py_filename + "w"
119 if os.path.exists(pyw_filename):
120 return pyw_filename
121 # Didn't find source, but it's probably the .py file we want.
122 return py_filename
123
124 elif filename.endswith("$py.class"):
125 # Jython is easy to guess.
126 return filename[:-9] + ".py"
127
128 # No idea, just use the file name as-is.
129 return filename
130
131
132 class PythonFileReporter(FileReporter):
133 """Report support for a Python file."""
134
135 def __init__(self, morf, coverage=None):
136 self.coverage = coverage
137
138 if hasattr(morf, '__file__') and morf.__file__:
139 filename = morf.__file__
140 elif isinstance(morf, types.ModuleType):
141 # A module should have had .__file__, otherwise we can't use it.
142 # This could be a PEP-420 namespace package.
143 raise CoverageException("Module {0} has no file".format(morf))
144 else:
145 filename = morf
146
147 filename = source_for_file(files.unicode_filename(filename))
148
149 super(PythonFileReporter, self).__init__(files.canonical_filename(filename))
150
151 if hasattr(morf, '__name__'):
152 name = morf.__name__.replace(".", os.sep)
153 if os.path.basename(filename).startswith('__init__.'):
154 name += os.sep + "__init__"
155 name += ".py"
156 name = files.unicode_filename(name)
157 else:
158 name = files.relative_filename(filename)
159 self.relname = name
160
161 self._source = None
162 self._parser = None
163 self._statements = None
164 self._excluded = None
165
166 def __repr__(self):
167 return "<PythonFileReporter {0!r}>".format(self.filename)
168
169 @contract(returns='unicode')
170 def relative_filename(self):
171 return self.relname
172
173 @property
174 def parser(self):
175 """Lazily create a :class:`PythonParser`."""
176 if self._parser is None:
177 self._parser = PythonParser(
178 filename=self.filename,
179 exclude=self.coverage._exclude_regex('exclude'),
180 )
181 self._parser.parse_source()
182 return self._parser
183
184 def lines(self):
185 """Return the line numbers of statements in the file."""
186 return self.parser.statements
187
188 def excluded_lines(self):
189 """Return the line numbers of statements in the file."""
190 return self.parser.excluded
191
192 def translate_lines(self, lines):
193 return self.parser.translate_lines(lines)
194
195 def translate_arcs(self, arcs):
196 return self.parser.translate_arcs(arcs)
197
198 @expensive
199 def no_branch_lines(self):
200 no_branch = self.parser.lines_matching(
201 join_regex(self.coverage.config.partial_list),
202 join_regex(self.coverage.config.partial_always_list)
203 )
204 return no_branch
205
206 @expensive
207 def arcs(self):
208 return self.parser.arcs()
209
210 @expensive
211 def exit_counts(self):
212 return self.parser.exit_counts()
213
214 def missing_arc_description(self, start, end, executed_arcs=None):
215 return self.parser.missing_arc_description(start, end, executed_arcs)
216
217 @contract(returns='unicode')
218 def source(self):
219 if self._source is None:
220 self._source = get_python_source(self.filename)
221 return self._source
222
223 def should_be_python(self):
224 """Does it seem like this file should contain Python?
225
226 This is used to decide if a file reported as part of the execution of
227 a program was really likely to have contained Python in the first
228 place.
229
230 """
231 # Get the file extension.
232 _, ext = os.path.splitext(self.filename)
233
234 # Anything named *.py* should be Python.
235 if ext.startswith('.py'):
236 return True
237 # A file with no extension should be Python.
238 if not ext:
239 return True
240 # Everything else is probably not Python.
241 return False
242
243 def source_token_lines(self):
244 return source_token_lines(self.source())

eric ide

mercurial