Plugins/CheckerPlugins/Pep8/Pep8Dialog.py

branch
Py2 comp.
changeset 2607
e5115553185a
parent 2525
8b507a9a2d40
child 2847
1843ef6e2656
equal deleted inserted replaced
2602:affc66a603c7 2607:e5115553185a
9 9
10 from __future__ import unicode_literals # __IGNORE_WARNING__ 10 from __future__ import unicode_literals # __IGNORE_WARNING__
11 11
12 import os 12 import os
13 import fnmatch 13 import fnmatch
14 import tokenize
14 15
15 from PyQt4.QtCore import pyqtSlot, Qt 16 from PyQt4.QtCore import pyqtSlot, Qt
16 from PyQt4.QtGui import QDialog, QTreeWidgetItem, QAbstractButton, \ 17 from PyQt4.QtGui import QDialog, QTreeWidgetItem, QAbstractButton, \
17 QDialogButtonBox, QApplication, QHeaderView 18 QDialogButtonBox, QApplication, QHeaderView
18 19
123 124
124 itm.setData(0, self.filenameRole, file) 125 itm.setData(0, self.filenameRole, file)
125 itm.setData(0, self.lineRole, int(line)) 126 itm.setData(0, self.lineRole, int(line))
126 itm.setData(0, self.positionRole, int(pos)) 127 itm.setData(0, self.positionRole, int(pos))
127 itm.setData(0, self.messageRole, message) 128 itm.setData(0, self.messageRole, message)
128 129
130 def __createErrorItem(self, file, line, pos, message):
131 """
132 Private method to create an entry in the result list.
133
134 @param file file name of the file (string)
135 @param line line number of issue (integer or string)
136 @param pos character position of issue (integer or string)
137 @param message message text (string)
138 @param fixed flag indicating a fixed issue (boolean)
139 """
140 if self.__lastFileItem is None:
141 # It's a new file
142 self.__lastFileItem = QTreeWidgetItem(self.resultList, [file])
143 self.__lastFileItem.setFirstColumnSpanned(True)
144 self.__lastFileItem.setExpanded(True)
145 self.__lastFileItem.setData(0, self.filenameRole, file)
146
147 itm = QTreeWidgetItem(self.__lastFileItem,
148 ["{0:6}".format(line), '', message])
149 itm.setIcon(0, UI.PixmapCache.getIcon("syntaxError.png"))
150
151 itm.setTextAlignment(0, Qt.AlignRight)
152 itm.setTextAlignment(1, Qt.AlignHCenter)
153
154 itm.setTextAlignment(0, Qt.AlignVCenter)
155 itm.setTextAlignment(1, Qt.AlignVCenter)
156 itm.setTextAlignment(2, Qt.AlignVCenter)
157
158 itm.setData(0, self.filenameRole, file)
159 itm.setData(0, self.lineRole, int(line))
160 itm.setData(0, self.positionRole, int(pos))
161 itm.setData(0, self.messageRole, message)
162
129 def __updateStatistics(self, statistics, fixer): 163 def __updateStatistics(self, statistics, fixer):
130 """ 164 """
131 Private method to update the collected statistics. 165 Private method to update the collected statistics.
132 166
133 @param statistics dictionary of statistical data with 167 @param statistics dictionary of statistical data with
220 254
221 if isinstance(fn, list): 255 if isinstance(fn, list):
222 files = fn[:] 256 files = fn[:]
223 elif os.path.isdir(fn): 257 elif os.path.isdir(fn):
224 files = [] 258 files = []
225 for ext in Preferences.getPython("Python3Extensions"): 259 extensions = set(Preferences.getPython("PythonExtensions") +
226 files.extend( 260 Preferences.getPython("Python3Extensions"))
227 Utilities.direntries(fn, 1, '*{0}'.format(ext), 0)) 261 for ext in extensions:
228 for ext in Preferences.getPython("PythonExtensions"): 262 files.extend(Utilities.direntries(fn, True, '*{0}'.format(ext), 0))
229 files.extend(
230 Utilities.direntries(fn, 1, '*{0}'.format(ext), 0))
231 else: 263 else:
232 files = [fn] 264 files = [fn]
233 265
234 # filter the list depending on the filter string 266 # filter the list depending on the filter string
235 if files: 267 if files:
239 for filter in filterList: 271 for filter in filterList:
240 files = \ 272 files = \
241 [f for f in files 273 [f for f in files
242 if not fnmatch.fnmatch(f, filter.strip())] 274 if not fnmatch.fnmatch(f, filter.strip())]
243 275
244 py3files = [f for f in files \ 276 if len(files) > 0:
245 if f.endswith( 277 self.checkProgress.setMaximum(len(files))
246 tuple(Preferences.getPython("Python3Extensions")))]
247 py2files = [f for f in files \
248 if f.endswith(
249 tuple(Preferences.getPython("PythonExtensions")))]
250
251 if len(py3files) + len(py2files) > 0:
252 self.checkProgress.setMaximum(len(py3files) + len(py2files))
253 QApplication.processEvents() 278 QApplication.processEvents()
254 279
255 # extract the configuration values 280 # extract the configuration values
256 excludeMessages = self.excludeMessagesEdit.text() 281 excludeMessages = self.excludeMessagesEdit.text()
257 includeMessages = self.includeMessagesEdit.text() 282 includeMessages = self.includeMessagesEdit.text()
264 self.resultList.setUpdatesEnabled(False) 289 self.resultList.setUpdatesEnabled(False)
265 self.resultList.setSortingEnabled(False) 290 self.resultList.setSortingEnabled(False)
266 291
267 # now go through all the files 292 # now go through all the files
268 progress = 0 293 progress = 0
269 for file in py3files + py2files: 294 for file in files:
270 self.checkProgress.setValue(progress) 295 self.checkProgress.setValue(progress)
271 QApplication.processEvents() 296 QApplication.processEvents()
272 297
273 if self.cancelled: 298 if self.cancelled:
274 self.__resort() 299 self.__resort()
279 try: 304 try:
280 source, encoding = Utilities.readEncodedFile(file) 305 source, encoding = Utilities.readEncodedFile(file)
281 source = source.splitlines(True) 306 source = source.splitlines(True)
282 except (UnicodeError, IOError) as msg: 307 except (UnicodeError, IOError) as msg:
283 self.noResults = False 308 self.noResults = False
284 self.__createResultItem(file, "1", "1", 309 self.__createResultItem(file, 1, 1,
285 self.trUtf8("Error: {0}").format(str(msg))\ 310 self.trUtf8("Error: {0}").format(str(msg))\
286 .rstrip()[1:-1], False) 311 .rstrip()[1:-1], False)
287 progress += 1 312 progress += 1
288 continue 313 continue
289 314
290 flags = Utilities.extractFlags(source)
291 ext = os.path.splitext(file)[1]
292 if fixIssues: 315 if fixIssues:
293 from .Pep8Fixer import Pep8Fixer 316 from .Pep8Fixer import Pep8Fixer
294 fixer = Pep8Fixer(self.__project, file, source, 317 fixer = Pep8Fixer(self.__project, file, source,
295 fixCodes, True) # always fix in place 318 fixCodes, True) # always fix in place
296 else: 319 else:
297 fixer = None 320 fixer = None
298 if ("FileType" in flags and 321 from .Pep8Checker import Pep8Checker
299 flags["FileType"] in ["Python", "Python2"]) or \ 322 checker = Pep8Checker(file, source,
300 file in py2files or \ 323 repeat=repeatMessages,
301 (ext in [".py", ".pyw"] and \ 324 select=includeMessages,
302 Preferences.getProject("DeterminePyFromProject") and \ 325 ignore=excludeMessages)
303 self.__project.isOpen() and \ 326 try:
304 self.__project.isProjectFile(file) and \ 327 checker.check_all()
305 self.__project.getProjectLanguage() in ["Python", 328 except tokenize.TokenError as msg:
306 "Python2"]): 329 self.noResults = False
307 from .Pep8Checker import Pep8Py2Checker 330 self.__createErrorItem(file, 1, -1,
308 checker = Pep8Py2Checker(file, [], 331 self.trUtf8("Token Error: {0}".format(str(msg))))
309 repeat=repeatMessages, 332 except IndentationError as err:
310 select=includeMessages, 333 self.noResults = False
311 ignore=excludeMessages) 334 self.__createErrorItem(file, err.lineno, -1,
335 self.trUtf8("Indentation Error: {0}".format(str(err.msg))))
336 except Exception as err:
337 self.noResults = False
338 self.__createErrorItem(file, 1, -1,
339 self.trUtf8("Unspecific Error: {0}".format(str(err))))
312 else: 340 else:
313 from .Pep8Checker import Pep8Checker 341 checker.messages.sort(key=lambda a: a[1])
314 checker = Pep8Checker(file, source, 342 for message in checker.messages:
315 repeat=repeatMessages, 343 fname, lineno, position, text = message
316 select=includeMessages, 344 if "__IGNORE_WARNING__" not in Utilities.extractLineFlags(
317 ignore=excludeMessages) 345 source[lineno - 1].strip()):
318 checker.check_all() 346 self.noResults = False
319 checker.messages.sort(key=lambda a: a[1]) 347 fixed = False
320 for message in checker.messages: 348 if fixer:
321 fname, lineno, position, text = message 349 fixed, msg = fixer.fixIssue(lineno, position, text)
322 if "__IGNORE_WARNING__" not in Utilities.extractLineFlags( 350 if fixed:
323 source[lineno - 1].strip()): 351 text += "\n" + \
324 self.noResults = False 352 self.trUtf8("Fix: {0}").format(msg)
325 fixed = False 353 self.__createResultItem(
326 if fixer: 354 fname, lineno, position, text, fixed)
327 fixed, msg = fixer.fixIssue(lineno, position, text) 355 if fixer:
328 if fixed: 356 fixer.saveFile(encoding)
329 text += "\n" + \ 357 self.__updateStatistics(checker.statistics, fixer)
330 self.trUtf8("Fix: {0}").format(msg) 358 finally:
331 self.__createResultItem( 359 progress += 1
332 fname, lineno, position, text, fixed)
333 fixer and fixer.saveFile(encoding)
334 self.__updateStatistics(checker.statistics, fixer)
335 progress += 1
336 finally: 360 finally:
337 # reenable updates of the list 361 # reenable updates of the list
338 self.resultList.setSortingEnabled(True) 362 self.resultList.setSortingEnabled(True)
339 self.resultList.setUpdatesEnabled(True) 363 self.resultList.setUpdatesEnabled(True)
340 self.checkProgress.setValue(progress) 364 self.checkProgress.setValue(progress)
448 472
449 vm = e5App().getObject("ViewManager") 473 vm = e5App().getObject("ViewManager")
450 vm.openSourceFile(fn, lineno=lineno, pos=position) 474 vm.openSourceFile(fn, lineno=lineno, pos=position)
451 editor = vm.getOpenEditor(fn) 475 editor = vm.getOpenEditor(fn)
452 476
453 editor.toggleFlakesWarning(lineno, True, message) 477 if position > 0:
478 editor.toggleFlakesWarning(lineno, True, message)
479 else:
480 error = message.split(':', 1)[-1]
481 editor.toggleSyntaxError(lineno, 1, True, error.strip(), show=True)
454 482
455 @pyqtSlot() 483 @pyqtSlot()
456 def on_showButton_clicked(self): 484 def on_showButton_clicked(self):
457 """ 485 """
458 Private slot to handle the "Show" button press. 486 Private slot to handle the "Show" button press.

eric ide

mercurial