Sun, 11 Apr 2021 18:45:10 +0200
Applied some more code simplifications suggested by the new Simplify checker (Y102: use single if) (batch 1).
--- a/eric6/CondaInterface/Conda.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/CondaInterface/Conda.py Sun Apr 11 18:45:10 2021 +0200 @@ -192,27 +192,26 @@ proc = QProcess() proc.start(exe, ["info", "--json"]) - if proc.waitForStarted(15000): - if proc.waitForFinished(15000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - jsonDict = json.loads(output) - except Exception: - jsonDict = {} - - if "envs" in jsonDict: - for prefix in jsonDict["envs"][:]: - if prefix == jsonDict["root_prefix"]: - if not jsonDict["root_writable"]: - # root prefix is listed but not writable - continue - name = self.RootName - else: - name = os.path.basename(prefix) - - environmentsList.append((name, prefix)) + if proc.waitForStarted(15000) and proc.waitForFinished(15000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + jsonDict = json.loads(output) + except Exception: + jsonDict = {} + + if "envs" in jsonDict: + for prefix in jsonDict["envs"][:]: + if prefix == jsonDict["root_prefix"]: + if not jsonDict["root_writable"]: + # root prefix is listed but not writable + continue + name = self.RootName + else: + name = os.path.basename(prefix) + + environmentsList.append((name, prefix)) return environmentsList @@ -259,28 +258,27 @@ proc = QProcess() proc.start(exe, args) - if proc.waitForStarted(15000): - if proc.waitForFinished(30000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - jsonList = json.loads(output) - except Exception: - jsonList = [] - - for package in jsonList: - if isinstance(package, dict): - packages.append(( - package["name"], - package["version"], - package["build_string"] - )) - else: - parts = package.rsplit("-", 2) - while len(parts) < 3: - parts.append("") - packages.append(tuple(parts)) + if proc.waitForStarted(15000) and proc.waitForFinished(30000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + jsonList = json.loads(output) + except Exception: + jsonList = [] + + for package in jsonList: + if isinstance(package, dict): + packages.append(( + package["name"], + package["version"], + package["build_string"] + )) + else: + parts = package.rsplit("-", 2) + while len(parts) < 3: + parts.append("") + packages.append(tuple(parts)) return packages @@ -326,30 +324,29 @@ proc = QProcess() proc.start(exe, args) - if proc.waitForStarted(15000): - if proc.waitForFinished(30000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - jsonDict = json.loads(output) - except Exception: - jsonDict = {} - - if "actions" in jsonDict and "LINK" in jsonDict["actions"]: - for linkEntry in jsonDict["actions"]["LINK"]: - if isinstance(linkEntry, dict): - packages.append(( - linkEntry["name"], - linkEntry["version"], - linkEntry["build_string"] - )) - else: - package = linkEntry.split()[0] - parts = package.rsplit("-", 2) - while len(parts) < 3: - parts.append("") - packages.append(tuple(parts)) + if proc.waitForStarted(15000) and proc.waitForFinished(30000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + jsonDict = json.loads(output) + except Exception: + jsonDict = {} + + if "actions" in jsonDict and "LINK" in jsonDict["actions"]: + for linkEntry in jsonDict["actions"]["LINK"]: + if isinstance(linkEntry, dict): + packages.append(( + linkEntry["name"], + linkEntry["version"], + linkEntry["build_string"] + )) + else: + package = linkEntry.split()[0] + parts = package.rsplit("-", 2) + while len(parts) < 3: + parts.append("") + packages.append(tuple(parts)) return packages @@ -588,17 +585,16 @@ proc = QProcess() proc.start(exe, args) - if proc.waitForStarted(15000): - if proc.waitForFinished(30000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - packages = json.loads(output) - ok = "error" not in packages - except Exception: # secok - # return values for errors is already set - pass + if proc.waitForStarted(15000) and proc.waitForFinished(30000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + packages = json.loads(output) + ok = "error" not in packages + except Exception: # secok + # return values for errors is already set + pass return ok, packages @@ -661,15 +657,14 @@ proc = QProcess() proc.start(exe, ["info", "--json"]) - if proc.waitForStarted(15000): - if proc.waitForFinished(30000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - infoDict = json.loads(output) - except Exception: - infoDict = {} + if proc.waitForStarted(15000) and proc.waitForFinished(30000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + infoDict = json.loads(output) + except Exception: + infoDict = {} return infoDict
--- a/eric6/CondaInterface/CondaPackagesWidget.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/CondaInterface/CondaPackagesWidget.py Sun Apr 11 18:45:10 2021 +0200 @@ -370,31 +370,30 @@ prefix=prefix, ) - if ok: - if result: - self.searchResultList.setUpdatesEnabled(False) - for package in result: - itm = QTreeWidgetItem(self.searchResultList, - [package]) - itm.setExpanded(False) - for detail in result[package]: - version = detail["version"] - build = detail["build"] - if "subdir" in detail: - platform = detail["subdir"] - elif "platform" in detail: - platform = detail["platform"] - else: - platform = "" - citm = QTreeWidgetItem( - itm, ["", version, build, platform]) - citm.setData(0, self.PackageDetailedDataRole, - detail) - - self.searchResultList.sortItems( - 0, Qt.SortOrder.AscendingOrder) - self.searchResultList.resizeColumnToContents(0) - self.searchResultList.setUpdatesEnabled(True) + if ok and result: + self.searchResultList.setUpdatesEnabled(False) + for package in result: + itm = QTreeWidgetItem(self.searchResultList, + [package]) + itm.setExpanded(False) + for detail in result[package]: + version = detail["version"] + build = detail["build"] + if "subdir" in detail: + platform = detail["subdir"] + elif "platform" in detail: + platform = detail["platform"] + else: + platform = "" + citm = QTreeWidgetItem( + itm, ["", version, build, platform]) + citm.setData(0, self.PackageDetailedDataRole, + detail) + + self.searchResultList.sortItems( + 0, Qt.SortOrder.AscendingOrder) + self.searchResultList.resizeColumnToContents(0) + self.searchResultList.setUpdatesEnabled(True) if not ok: try: message = result["message"]
--- a/eric6/Cooperation/Connection.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Cooperation/Connection.py Sun Apr 11 18:45:10 2021 +0200 @@ -240,9 +240,11 @@ self.readyForUse.emit() while self.bytesAvailable(): - if self.__currentDataType == Connection.Undefined: - if not self.__readProtocolHeader(): - return + if ( + self.__currentDataType == Connection.Undefined and + not self.__readProtocolHeader() + ): + return if not self.__hasEnoughData(): return
--- a/eric6/DataViews/CodeMetrics.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/DataViews/CodeMetrics.py Sun Apr 11 18:45:10 2021 +0200 @@ -233,9 +233,11 @@ stats.indent(tok) elif tok.type == DEDENT: stats.dedent(tok) - elif tok.type == KEYWORD: - if tok.text in ("class", "def"): - stats.push(parser.tokenlist[idx + 1].text, tok.row) + elif ( + tok.type == KEYWORD and + tok.text in ("class", "def") + ): + stats.push(parser.tokenlist[idx + 1].text, tok.row) # collect overall statistics summarize(total, 'lines', parser.lines)
--- a/eric6/DataViews/PyProfileDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/DataViews/PyProfileDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -179,34 +179,37 @@ if self.cancelled: return - if (not (self.ericpath and + if ( + not (self.ericpath and func[0].startswith(self.ericpath)) and not func[0].startswith("DebugClients") and func[0] != "profile" and not (exclude and (func[0].startswith(self.pyLibPath) or func[0] == "") - )): - if (self.file is None or func[0].startswith(self.file) or - func[0].startswith(self.pyLibPath)): - # calculate the totals - total_calls += nc - prim_calls += cc - total_tt += tt - - if nc != cc: - c = "{0:d}/{1:d}".format(nc, cc) - else: - c = str(nc) - if nc == 0: - tpc = "{0: 8.3f}".format(0.0) - else: - tpc = "{0: 8.3f}".format(tt / nc) - if cc == 0: - cpc = "{0: 8.3f}".format(0.0) - else: - cpc = "{0: 8.3f}".format(ct / cc) - self.__createResultItem(c, tt, tpc, ct, cpc, func[0], - func[1], func[2]) + ) and + (self.file is None or + func[0].startswith(self.file) or + func[0].startswith(self.pyLibPath)) + ): + # calculate the totals + total_calls += nc + prim_calls += cc + total_tt += tt + + if nc != cc: + c = "{0:d}/{1:d}".format(nc, cc) + else: + c = str(nc) + if nc == 0: + tpc = "{0: 8.3f}".format(0.0) + else: + tpc = "{0: 8.3f}".format(tt / nc) + if cc == 0: + cpc = "{0: 8.3f}".format(0.0) + else: + cpc = "{0: 8.3f}".format(ct / cc) + self.__createResultItem(c, tt, tpc, ct, cpc, func[0], + func[1], func[2]) self.checkProgress.setValue(progress) QApplication.processEvents()
--- a/eric6/DebugClients/Python/MultiProcessDebugExtension.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/DebugClients/Python/MultiProcessDebugExtension.py Sun Apr 11 18:45:10 2021 +0200 @@ -306,20 +306,23 @@ frame = None # Just make sure we don't hold on to it. childProcess = getattr(os, originalName)() # fork - if not childProcess and not isMultiprocessingPopen: - if isNewPythonProcess: - (wd, host, port, exceptions, tracePython, redirect, - noencoding) = _debugClient.startOptions - _debugClient.startDebugger( - filename=sys.argv[0], - host=host, - port=port, - enableTrace=multiprocess and not isSubprocessFork, - exceptions=exceptions, - tracePython=tracePython, - redirect=redirect, - passive=False, - multiprocessSupport=multiprocess) + if ( + not childProcess and + not isMultiprocessingPopen and + isNewPythonProcess + ): + (wd, host, port, exceptions, tracePython, redirect, + noencoding) = _debugClient.startOptions + _debugClient.startDebugger( + filename=sys.argv[0], + host=host, + port=port, + enableTrace=multiprocess and not isSubprocessFork, + exceptions=exceptions, + tracePython=tracePython, + redirect=redirect, + passive=False, + multiprocessSupport=multiprocess) return childProcess return newFork
--- a/eric6/Debugger/BreakPointModel.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Debugger/BreakPointModel.py Sun Apr 11 18:45:10 2021 +0200 @@ -102,17 +102,23 @@ elif index.column() in (1, 2, 5): return self.breakpoints[index.row()][index.column()] - if role == Qt.ItemDataRole.CheckStateRole: - if index.column() in (3, 4): - return self.breakpoints[index.row()][index.column()] + if ( + role == Qt.ItemDataRole.CheckStateRole and + index.column() in (3, 4) + ): + return self.breakpoints[index.row()][index.column()] - if role == Qt.ItemDataRole.ToolTipRole: - if index.column() in (0, 2): - return self.breakpoints[index.row()][index.column()] + if ( + role == Qt.ItemDataRole.ToolTipRole and + index.column() in (0, 2) + ): + return self.breakpoints[index.row()][index.column()] - if role == Qt.ItemDataRole.TextAlignmentRole: - if index.column() < len(self.alignments): - return self.alignments[index.column()] + if ( + role == Qt.ItemDataRole.TextAlignmentRole and + index.column() < len(self.alignments) + ): + return self.alignments[index.column()] return None
--- a/eric6/Debugger/DebugServer.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Debugger/DebugServer.py Sun Apr 11 18:45:10 2021 +0200 @@ -508,11 +508,14 @@ """ self.running = False - if not self.passive or not self.passiveClientExited: - if self.debuggerInterface and self.debuggerInterface.isConnected(): - self.shutdownServer() - self.debugging = False - self.clientGone.emit(unplanned and self.debugging) + if ( + (not self.passive or not self.passiveClientExited) and + self.debuggerInterface and + self.debuggerInterface.isConnected() + ): + self.shutdownServer() + self.debugging = False + self.clientGone.emit(unplanned and self.debugging) if clType: if clType not in self.getSupportedLanguages():
--- a/eric6/Debugger/DebugUI.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Debugger/DebugUI.py Sun Apr 11 18:45:10 2021 +0200 @@ -1310,9 +1310,11 @@ self.ui.setDebugProfile() self.debugActGrp.setEnabled(True) return - elif res == E5MessageBox.Ignore: - if exceptionType not in self.excIgnoreList: - self.excIgnoreList.append(exceptionType) + elif ( + res == E5MessageBox.Ignore and + exceptionType not in self.excIgnoreList + ): + self.excIgnoreList.append(exceptionType) if self.lastAction != -1: if self.lastAction == 2:
--- a/eric6/Debugger/DebuggerInterfacePython.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Debugger/DebuggerInterfacePython.py Sun Apr 11 18:45:10 2021 +0200 @@ -367,9 +367,8 @@ debugClient = project.getDebugProperty("DEBUGCLIENT") if not venvName: venvName = project.getDebugProperty("VIRTUALENV") - if not venvName: - if project.getProjectLanguage() == "Python3": - venvName = Preferences.getDebugger("Python3VirtualEnv") + if not venvName and project.getProjectLanguage() == "Python3": + venvName = Preferences.getDebugger("Python3VirtualEnv") if configOverride and configOverride["enable"]: redirect = str(configOverride["redirect"])
--- a/eric6/Debugger/VariablesViewer.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Debugger/VariablesViewer.py Sun Apr 11 18:45:10 2021 +0200 @@ -497,15 +497,18 @@ if posPaths: for child in parent.children: - if child.hasChildren and child.nameWithId in posPaths: - if child.currentCount >= 0: - # Discard loaded elements and refresh if still expanded - child.currentCount = -1 - child.populated = False - row = parent.children.index(child) - newParentIdx = self.index(row, 0, parentIdx) - self.resetModifiedMarker( - newParentIdx, pathlist + (child.nameWithId,)) + if ( + child.hasChildren and + child.nameWithId in posPaths and + child.currentCount >= 0 + ): + # Discard loaded elements and refresh if still expanded + child.currentCount = -1 + child.populated = False + row = parent.children.index(child) + newParentIdx = self.index(row, 0, parentIdx) + self.resetModifiedMarker( + newParentIdx, pathlist + (child.nameWithId,)) self.closedItems = []
--- a/eric6/Debugger/WatchPointModel.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Debugger/WatchPointModel.py Sun Apr 11 18:45:10 2021 +0200 @@ -77,21 +77,29 @@ if not index.isValid(): return None - if role == Qt.ItemDataRole.DisplayRole: - if index.column() in [0, 1, 4]: - return self.watchpoints[index.row()][index.column()] + if ( + role == Qt.ItemDataRole.DisplayRole and + index.column() in [0, 1, 4] + ): + return self.watchpoints[index.row()][index.column()] - if role == Qt.ItemDataRole.CheckStateRole: - if index.column() in [2, 3]: - return self.watchpoints[index.row()][index.column()] + if ( + role == Qt.ItemDataRole.CheckStateRole and + index.column() in [2, 3] + ): + return self.watchpoints[index.row()][index.column()] - if role == Qt.ItemDataRole.ToolTipRole: - if index.column() in [0, 1]: - return self.watchpoints[index.row()][index.column()] + if ( + role == Qt.ItemDataRole.ToolTipRole and + index.column() in [0, 1] + ): + return self.watchpoints[index.row()][index.column()] - if role == Qt.ItemDataRole.TextAlignmentRole: - if index.column() < len(self.alignments): - return self.alignments[index.column()] + if ( + role == Qt.ItemDataRole.TextAlignmentRole and + index.column() < len(self.alignments) + ): + return self.alignments[index.column()] return None
--- a/eric6/DocumentationTools/APIGenerator.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/DocumentationTools/APIGenerator.py Sun Apr 11 18:45:10 2021 +0200 @@ -56,11 +56,13 @@ self.includePrivate = includePrivate classNames = sorted(list(self.module.classes.keys())) for className in classNames: - if not self.__isPrivate(self.module.classes[className]): - if className not in bases: - bases[className] = [ - b for b in self.module.classes[className].super - if b != "object"] + if ( + not self.__isPrivate(self.module.classes[className]) and + className not in bases + ): + bases[className] = [ + b for b in self.module.classes[className].super + if b != "object"] return bases def __isPrivate(self, obj):
--- a/eric6/E5Gui/E5ModelToolBar.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/E5Gui/E5ModelToolBar.py Sun Apr 11 18:45:10 2021 +0200 @@ -175,9 +175,11 @@ idx = self.index(act) if idx.isValid(): self.activated[QModelIndex].emit(idx) - elif evt.type() == QEvent.Type.MouseButtonPress: - if evt.buttons() & Qt.MouseButton.LeftButton: - self.__dragStartPosition = self.mapFromGlobal(evt.globalPos()) + elif ( + evt.type() == QEvent.Type.MouseButtonPress and + evt.buttons() & Qt.MouseButton.LeftButton + ): + self.__dragStartPosition = self.mapFromGlobal(evt.globalPos()) return False
--- a/eric6/Graphics/GraphicsUtilities.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Graphics/GraphicsUtilities.py Sun Apr 11 18:45:10 2021 +0200 @@ -65,11 +65,13 @@ for current in stage: currentParents = parents.get(current, []) for parent in currentParents: - if parent in stage and parent != current: - # might wind up removing current - if current not in parents.get(parent, []): - # is not mutually dependant - removes.append(current) + if ( + parent in stage and + parent != current and + current not in parents.get(parent, []) + ): + # is not mutually dependant + removes.append(current) for remove in removes: while remove in stage:
--- a/eric6/Graphics/UMLGraphicsView.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Graphics/UMLGraphicsView.py Sun Apr 11 18:45:10 2021 +0200 @@ -520,6 +520,7 @@ amount = rect.y() + rect.height() index = i elif alignment == Qt.AlignmentFlag.AlignVCenter: + # __IGNORE_WARNING_Y102__ if amount is None or rect.height() > amount: amount = rect.height() index = i
--- a/eric6/HexEdit/HexEditMainWindow.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/HexEdit/HexEditMainWindow.py Sun Apr 11 18:45:10 2021 +0200 @@ -940,9 +940,12 @@ """ Private slot called to open a binary file in new hex editor window. """ - if not self.__lastOpenPath: - if self.__project and self.__project.isOpen(): - self.__lastOpenPath = self.__project.getProjectPath() + if ( + not self.__lastOpenPath and + self.__project is not None and + self.__project.isOpen() + ): + self.__lastOpenPath = self.__project.getProjectPath() fileName = E5FileDialog.getOpenFileName( self, @@ -1012,9 +1015,12 @@ Private slot to open a binary file. """ if self.__maybeSave(): - if not self.__lastOpenPath: - if self.__project and self.__project.isOpen(): - self.__lastOpenPath = self.__project.getProjectPath() + if ( + not self.__lastOpenPath and + self.__project is not None and + self.__project.isOpen() + ): + self.__lastOpenPath = self.__project.getProjectPath() fileName = E5FileDialog.getOpenFileName( self, @@ -1057,9 +1063,12 @@ @return flag indicating success @rtype bool """ - if not self.__lastSavePath: - if self.__project and self.__project.isOpen(): - self.__lastSavePath = self.__project.getProjectPath() + if ( + not self.__lastSavePath and + self.__project is not None and + self.__project.isOpen() + ): + self.__lastSavePath = self.__project.getProjectPath() if not self.__lastSavePath and self.__lastOpenPath: self.__lastSavePath = self.__lastOpenPath @@ -1136,9 +1145,12 @@ @type bool """ savePath = self.__lastSavePath - if not savePath: - if self.__project and self.__project.isOpen(): - savePath = self.__project.getProjectPath() + if ( + not savePath and + self.__project is not None and + self.__project.isOpen() + ): + savePath = self.__project.getProjectPath() if not savePath and self.__lastOpenPath: savePath = self.__lastOpenPath @@ -1418,10 +1430,7 @@ self.__recentMenu.clear() for idx, rs in enumerate(self.__recent, start=1): - if idx < 10: - formatStr = '&{0:d}. {1}' - else: - formatStr = '{0:d}. {1}' + formatStr = '&{0:d}. {1}' if idx < 10 else '{0:d}. {1}' act = self.__recentMenu.addAction( formatStr.format( idx,
--- a/eric6/HexEdit/HexEditUndoStack.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/HexEdit/HexEditUndoStack.py Sun Apr 11 18:45:10 2021 +0200 @@ -89,11 +89,13 @@ """ result = False - if self._cmd != HexEditCommand.RemoveAt: - if command._cmd == HexEditCommand.Overwrite: - if command._pos == self._pos: - self._newByte = command._newByte - result = True + if ( + self._cmd != HexEditCommand.RemoveAt and + command._cmd == HexEditCommand.Overwrite and + command._pos == self._pos + ): + self._newByte = command._newByte + result = True return result
--- a/eric6/HexEdit/HexEditWidget.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/HexEdit/HexEditWidget.py Sun Apr 11 18:45:10 2021 +0200 @@ -1287,9 +1287,11 @@ self.__resetSelection(2 * self.__bPosCurrent) # if in insert mode, insert a byte - if not self.__overwriteMode: - if (self.__cursorPosition % 2) == 0: - self.insert(self.__bPosCurrent, 0) + if ( + not self.__overwriteMode and + (self.__cursorPosition % 2) == 0 + ): + self.insert(self.__bPosCurrent, 0) # change content if self.__chunks.size() > 0: @@ -1427,11 +1429,13 @@ ): c = self.__selectionBrush.color() painter.setPen(self.__selectionPen) - elif self.__highlighting: - if self.__markedShown and self.__markedShown[ - posBa - self.__bPosFirst]: - c = self.__highlightingBrush.color() - painter.setPen(self.__highlightingPen) + elif ( + self.__highlighting and + self.__markedShown and + self.__markedShown[posBa - self.__bPosFirst] + ): + c = self.__highlightingBrush.color() + painter.setPen(self.__highlightingPen) # render hex value r = QRect()
--- a/eric6/IconEditor/IconEditorGrid.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/IconEditor/IconEditorGrid.py Sun Apr 11 18:45:10 2021 +0200 @@ -549,10 +549,12 @@ @param evt reference to the mouse event object (QMouseEvent) """ if evt.button() == Qt.MouseButton.LeftButton: - if self.__curTool in [self.Pencil, self.Rubber]: - if self.__currentUndoCmd: - self.__currentUndoCmd.setAfterImage(self.__image) - self.__currentUndoCmd = None + if ( + self.__curTool in [self.Pencil, self.Rubber] and + self.__currentUndoCmd + ): + self.__currentUndoCmd.setAfterImage(self.__image) + self.__currentUndoCmd = None if self.__curTool not in [self.Pencil, self.Rubber, self.Fill, self.ColorPicker, @@ -857,16 +859,18 @@ img.fill(qRgba(0, 0, 0, 0)) for i in range(0, self.__selRect.width()): for j in range(0, self.__selRect.height()): - if self.__image.rect().contains(self.__selRect.x() + i, - self.__selRect.y() + j): - if self.__isMarked( - self.__selRect.x() + i, self.__selRect.y() + j): - img.setPixel(i, j, self.__image.pixel( - self.__selRect.x() + i, self.__selRect.y() + j)) - if cut: - self.__image.setPixel(self.__selRect.x() + i, - self.__selRect.y() + j, - qRgba(0, 0, 0, 0)) + if ( + self.__image.rect().contains( + self.__selRect.x() + i, self.__selRect.y() + j) and + self.__isMarked(self.__selRect.x() + i, + self.__selRect.y() + j) + ): + img.setPixel(i, j, self.__image.pixel( + self.__selRect.x() + i, self.__selRect.y() + j)) + if cut: + self.__image.setPixel(self.__selRect.x() + i, + self.__selRect.y() + j, + qRgba(0, 0, 0, 0)) if cut: self.__undoStack.push(cmd)
--- a/eric6/IconEditor/IconEditorWindow.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/IconEditor/IconEditorWindow.py Sun Apr 11 18:45:10 2021 +0200 @@ -1066,9 +1066,12 @@ Private slot to open an icon file. """ if self.__maybeSave(): - if not self.__lastOpenPath: - if self.__project and self.__project.isOpen(): - self.__lastOpenPath = self.__project.getProjectPath() + if ( + not self.__lastOpenPath and + self.__project is not None and + self.__project.isOpen() + ): + self.__lastOpenPath = self.__project.getProjectPath() fileName = E5FileDialog.getOpenFileNameAndFilter( self, @@ -1098,9 +1101,12 @@ @return flag indicating success (boolean) """ - if not self.__lastSavePath: - if self.__project and self.__project.isOpen(): - self.__lastSavePath = self.__project.getProjectPath() + if ( + not self.__lastSavePath and + self.__project is not None and + self.__project.isOpen() + ): + self.__lastSavePath = self.__project.getProjectPath() if not self.__lastSavePath and self.__lastOpenPath: self.__lastSavePath = self.__lastOpenPath
--- a/eric6/MicroPython/MicroPythonDevices.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/MicroPython/MicroPythonDevices.py Sun Apr 11 18:45:10 2021 +0200 @@ -210,16 +210,18 @@ continue for board in SupportedBoards: - if ((vid, pid) in SupportedBoards[board]["ids"] or - (vid, None) in SupportedBoards[board]["ids"]): - if board in ("bbc_microbit", "calliope"): + if ( + (vid, pid) in SupportedBoards[board]["ids"] or + (vid, None) in SupportedBoards[board]["ids"] + ): + if ( + board in ("bbc_microbit", "calliope") and + (port.description().strip() != + SupportedBoards[board]["port_description"]) + ): # both boards have the same VID and PID # try to differentiate based on port description - if ( - port.description().strip() != - SupportedBoards[board]["port_description"] - ): - continue + continue foundDevices.append(( board, port.description(), @@ -229,19 +231,18 @@ pid, )) supported = True - if not supported: + if not supported and (vid, pid) in manualDevices: # check the locally added ones next - if (vid, pid) in manualDevices: - board = manualDevices[(vid, pid)]["type"] - foundDevices.append(( - board, - port.description(), - SupportedBoards[board]["description"], - port.portName(), - vid, - pid, - )) - supported = True + board = manualDevices[(vid, pid)]["type"] + foundDevices.append(( + board, + port.description(), + SupportedBoards[board]["description"], + port.portName(), + vid, + pid, + )) + supported = True if not supported: if vid and pid: if (vid, pid) not in IgnoredBoards:
--- a/eric6/MicroPython/UF2FlashDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/MicroPython/UF2FlashDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -466,13 +466,15 @@ continue for board in SupportedUF2Boards: - if not boardType or (board.startswith(boardType)): - if (vid, pid) in SupportedUF2Boards[board]["volumes"]: - foundDevices.append(( - board, - port.description(), - (vid, pid), - )) + if ( + (not boardType or (board.startswith(boardType))) and + (vid, pid) in SupportedUF2Boards[board]["volumes"] + ): + foundDevices.append(( + board, + port.description(), + (vid, pid), + )) # second run for boards needing special treatment (e.g. RP2040) for board in SupportedUF2Boards:
--- a/eric6/MultiProject/MultiProject.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/MultiProject/MultiProject.py Sun Apr 11 18:45:10 2021 +0200 @@ -1001,14 +1001,14 @@ reopened, if it has been opened already (boolean) """ for project in self.__projects.values(): - if project['master']: - if ( - reopen or - not self.projectObject.isOpen() or - self.projectObject.getProjectFile() != project['file'] - ): - self.openProject(project['file']) - return + if ( + project['master'] and + (reopen or + not self.projectObject.isOpen() or + self.projectObject.getProjectFile() != project['file']) + ): + self.openProject(project['file']) + return def getMasterProjectFile(self): """
--- a/eric6/Network/IRC/IrcChannelWidget.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Network/IRC/IrcChannelWidget.py Sun Apr 11 18:45:10 2021 +0200 @@ -96,11 +96,10 @@ """ oper = privilege[0] priv = privilege[1] - if oper == "+": - if priv in IrcUserItem.PrivilegeMapping: + if priv in IrcUserItem.PrivilegeMapping: + if oper == "+": self.__privilege |= IrcUserItem.PrivilegeMapping[priv] - elif oper == "-": - if priv in IrcUserItem.PrivilegeMapping: + elif oper == "-": self.__privilege &= ~IrcUserItem.PrivilegeMapping[priv] self.__setIcon() @@ -634,9 +633,8 @@ """ for patternRe, patternFunc in self.__patterns: match = patternRe.match(line) - if match is not None: - if patternFunc(match): - return True + if match is not None and patternFunc(match): + return True return False
--- a/eric6/Network/IRC/IrcIdentitiesEditDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Network/IRC/IrcIdentitiesEditDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -80,10 +80,13 @@ @param evt reference to the event (QEvent) @return flag indicating that the event should be filtered out (boolean) """ - if obj == self.nicknameEdit and evt.type() == QEvent.Type.KeyPress: - if evt.key() in [Qt.Key.Key_Enter, Qt.Key.Key_Return]: - self.on_nicknameAddButton_clicked() - return True + if ( + obj == self.nicknameEdit and + evt.type() == QEvent.Type.KeyPress and + evt.key() in [Qt.Key.Key_Enter, Qt.Key.Key_Return] + ): + self.on_nicknameAddButton_clicked() + return True return super().eventFilter(obj, evt)
--- a/eric6/Network/IRC/IrcWidget.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Network/IRC/IrcWidget.py Sun Apr 11 18:45:10 2021 +0200 @@ -603,9 +603,8 @@ # step 2: try to process the message ourselves for patternRe, patternFunc in self.__patterns: match = patternRe.match(line) - if match is not None: - if patternFunc(match): - break + if match is not None and patternFunc(match): + break else: # Oops, the message wasn't handled self.networkWidget.addErrorMessage( @@ -682,19 +681,21 @@ # :foo MODE foo :+i name, modes = match.group(3).split(" :") sourceNick = match.group(1) - if not self.isChannelName(name): - if name == self.__nickName: - if sourceNick == self.__nickName: - msg = self.tr( - "You have set your personal modes to" - " <b>[{0}]</b>.").format(modes) - else: - msg = self.tr( - "{0} has changed your personal modes to" - " <b>[{1}]</b>.").format(sourceNick, modes) - self.networkWidget.addServerMessage( - self.tr("Mode"), msg, filterMsg=False) - return True + if ( + not self.isChannelName(name) and + name == self.__nickName + ): + if sourceNick == self.__nickName: + msg = self.tr( + "You have set your personal modes to" + " <b>[{0}]</b>.").format(modes) + else: + msg = self.tr( + "{0} has changed your personal modes to" + " <b>[{1}]</b>.").format(sourceNick, modes) + self.networkWidget.addServerMessage( + self.tr("Mode"), msg, filterMsg=False) + return True elif name == "PART": nick = match.group(1).split("!", 1)[0] if nick == self.__nickName:
--- a/eric6/PipInterface/Pip.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/PipInterface/Pip.py Sun Apr 11 18:45:10 2021 +0200 @@ -583,22 +583,21 @@ proc = QProcess() proc.start(interpreter, args) - if proc.waitForStarted(15000): - if proc.waitForFinished(30000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - jsonList = json.loads(output) - except Exception: - jsonList = [] - - for package in jsonList: - if isinstance(package, dict): - packages.append(( - package["name"], - package["version"], - )) + if proc.waitForStarted(15000) and proc.waitForFinished(30000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + jsonList = json.loads(output) + except Exception: + jsonList = [] + + for package in jsonList: + if isinstance(package, dict): + packages.append(( + package["name"], + package["version"], + )) return packages @@ -645,23 +644,22 @@ proc = QProcess() proc.start(interpreter, args) - if proc.waitForStarted(15000): - if proc.waitForFinished(30000): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), - 'replace').strip() - try: - jsonList = json.loads(output) - except Exception: - jsonList = [] - - for package in jsonList: - if isinstance(package, dict): - packages.append(( - package["name"], - package["version"], - package["latest_version"], - )) + if proc.waitForStarted(15000) and proc.waitForFinished(30000): + output = str(proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + 'replace').strip() + try: + jsonList = json.loads(output) + except Exception: + jsonList = [] + + for package in jsonList: + if isinstance(package, dict): + packages.append(( + package["name"], + package["version"], + package["latest_version"], + )) return packages
--- a/eric6/PipInterface/PipPackageDetailsDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/PipInterface/PipPackageDetailsDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -193,13 +193,12 @@ text = self.tr("any") elif text is None: text = "" - if forUrl: - if ( - not isinstance(text, str) or - not text.startswith(("http://", "https://", "ftp://")) - ): - # ignore if the schema is not one of the listed ones - text = "" + if forUrl and ( + not isinstance(text, str) or + not text.startswith(("http://", "https://", "ftp://")) + ): + # ignore if the schema is not one of the listed ones + text = "" return text
--- a/eric6/PluginManager/PluginManager.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/PluginManager/PluginManager.py Sun Apr 11 18:45:10 2021 +0200 @@ -1166,14 +1166,16 @@ list(self.__onDemandActiveModules.values()) + list(self.__onDemandInactiveModules.values()) ): - if getattr(module, "pluginType", "") == "version_control": - if hasattr(module, "getVcsSystemIndicator"): - res = module.getVcsSystemIndicator() - for indicator, vcsData in list(res.items()): - if indicator in vcsDict: - vcsDict[indicator].append(vcsData) - else: - vcsDict[indicator] = [vcsData] + if ( + getattr(module, "pluginType", "") == "version_control" and + hasattr(module, "getVcsSystemIndicator") + ): + res = module.getVcsSystemIndicator() + for indicator, vcsData in list(res.items()): + if indicator in vcsDict: + vcsDict[indicator].append(vcsData) + else: + vcsDict[indicator] = [vcsData] return vcsDict @@ -1433,9 +1435,11 @@ list(self.__activeModules.values()) + list(self.__inactiveModules.values()) ): - if getattr(module, "pluginType", "") == type_: - if hasattr(module, "clearPrivateData"): - module.clearPrivateData() + if ( + getattr(module, "pluginType", "") == type_ and + hasattr(module, "clearPrivateData") + ): + module.clearPrivateData() # # eflag: noqa = M801
--- a/eric6/PluginManager/PluginRepositoryDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/PluginManager/PluginRepositoryDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -534,9 +534,8 @@ @param reply reference to the network reply @type QNetworkReply """ - if reply is None: - if self.__replies: - reply = self.__replies[0] + if reply is None and bool(self.__replies): + reply = self.__replies[0] self.__pluginsToDownload = [] if reply is not None: reply.abort()
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Annotations/AnnotationsChecker.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Annotations/AnnotationsChecker.py Sun Apr 11 18:45:10 2021 +0200 @@ -371,14 +371,13 @@ @type str """ # check class method issues - if methodType != "function": - if argNode.arg in ("cls", "self"): - if methodType == "classmethod": - self.issues.append((argNode, "A102")) - return - elif methodType != "staticmethod": - self.issues.append((argNode, "A101")) - return + if methodType != "function" and argNode.arg in ("cls", "self"): + if methodType == "classmethod": + self.issues.append((argNode, "A102")) + return + elif methodType != "staticmethod": + self.issues.append((argNode, "A101")) + return # check all other arguments if argType == "kwarg":
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py Sun Apr 11 18:45:10 2021 +0200 @@ -972,9 +972,11 @@ return summary, lineNumber = self.__getSummaryLine(docstringContext) - if len(docstrings) > 2: - if docstrings[lineNumber + 1].strip(): - self.__error(docstringContext.start() + lineNumber, 0, "D144") + if ( + len(docstrings) > 2 and + docstrings[lineNumber + 1].strip() + ): + self.__error(docstringContext.start() + lineNumber, 0, "D144") def __checkBlankAfterLastParagraph(self, docstringContext, context): """ @@ -1285,9 +1287,11 @@ return summaryLines, lineNumber = self.__getSummaryLines(docstringContext) - if len(docstrings) - 2 > lineNumber + len(summaryLines) - 1: - if docstrings[lineNumber + len(summaryLines)].strip(): - self.__error(docstringContext.start() + lineNumber, 0, "D246") + if ( + len(docstrings) - 2 > lineNumber + len(summaryLines) - 1 and + docstrings[lineNumber + len(summaryLines)].strip() + ): + self.__error(docstringContext.start() + lineNumber, 0, "D246") def __checkEricNoBlankBeforeAndAfterClassOrFunction( self, docstringContext, context):
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py Sun Apr 11 18:45:10 2021 +0200 @@ -543,14 +543,12 @@ # if starargs or kwargs is not None, it can't count the # parameters but at least check if the args are used - if hasKwArgs: - if not names: - # No names but kwargs - self.__error(call.lineno - 1, call.col_offset, "M623") - if hasStarArgs: - if not numbers: - # No numbers but args - self.__error(call.lineno - 1, call.col_offset, "M624") + if hasKwArgs and not names: + # No names but kwargs + self.__error(call.lineno - 1, call.col_offset, "M623") + if hasStarArgs and not numbers: + # No numbers but args + self.__error(call.lineno - 1, call.col_offset, "M624") if not hasKwArgs and not hasStarArgs: # can actually verify numbers and names @@ -1199,11 +1197,14 @@ @type ast.Call """ # we are in a logging statement - if self.__withinLoggingStatement(): - if self.__withinLoggingArgument() and self.__isFormatCall(node): - self.violations.append((node, "M651")) - super().generic_visit(node) - return + if ( + self.__withinLoggingStatement() and + self.__withinLoggingArgument() and + self.__isFormatCall(node) + ): + self.violations.append((node, "M651")) + super().generic_visit(node) + return loggingLevel = self.__detectLoggingLevel(node) @@ -1265,12 +1266,14 @@ @param node reference to the node to be processed @type ast.JoinedStr """ - if self.__withinLoggingStatement(): - if any(isinstance(i, ast.FormattedValue) for i in node.values): - if self.__withinLoggingArgument(): - self.violations.append((node, "M654")) - - super().generic_visit(node) + if ( + self.__withinLoggingStatement() and + any(isinstance(i, ast.FormattedValue) for i in node.values) and + self.__withinLoggingArgument() + ): + self.violations.append((node, "M654")) + + super().generic_visit(node) class BugBearVisitor(ast.NodeVisitor): @@ -1423,10 +1426,10 @@ target = node.targets[0] if ( isinstance(target, ast.Attribute) and - isinstance(target.value, ast.Name) + isinstance(target.value, ast.Name) and + (target.value.id, target.attr) == ('os', 'environ') ): - if (target.value.id, target.attr) == ('os', 'environ'): - self.violations.append((node, "M506")) + self.violations.append((node, "M506")) self.generic_visit(node)
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Naming/NamingStyleChecker.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Naming/NamingStyleChecker.py Sun Apr 11 18:45:10 2021 +0200 @@ -342,15 +342,21 @@ yield self.__error(node, "N804") return - if functionType == "method": - if argNames[0] != "self": - yield self.__error(node, "N805") - elif functionType == "classmethod": - if argNames[0] != "cls": - yield self.__error(node, "N804") - elif functionType == "staticmethod": - if argNames[0] in ("cls", "self"): - yield self.__error(node, "N806") + if ( + functionType == "method" and + argNames[0] != "self" + ): + yield self.__error(node, "N805") + elif ( + functionType == "classmethod" and + argNames[0] != "cls" + ): + yield self.__error(node, "N804") + elif ( + functionType == "staticmethod" and + argNames[0] in ("cls", "self") + ): + yield self.__error(node, "N806") for arg in argNames: if not self.LowercaseRegex.match(arg): yield self.__error(node, "N803")
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/blackListImports.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/blackListImports.py Sun Apr 11 18:45:10 2021 +0200 @@ -107,9 +107,11 @@ if nodeType.startswith('Import'): prefix = "" - if nodeType == "ImportFrom": - if context.node.module is not None: - prefix = context.node.module + "." + if ( + nodeType == "ImportFrom" and + context.node.module is not None + ): + prefix = context.node.module + "." for code in _blacklists: qualnames, severity = _blacklists[code]
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/certificateValidation.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/certificateValidation.py Sun Apr 11 18:45:10 2021 +0200 @@ -45,13 +45,13 @@ http_verbs = ('get', 'options', 'head', 'post', 'put', 'patch', 'delete') if ( 'requests' in context.callFunctionNameQual and - context.callFunctionName in http_verbs + context.callFunctionName in http_verbs and + context.checkCallArgValue('verify', 'False') ): - if context.checkCallArgValue('verify', 'False'): - reportError( - context.getLinenoForCallArg('verify') - 1, - context.getOffsetForCallArg('verify'), - "S501", - "H", - "H" - ) + reportError( + context.getLinenoForCallArg('verify') - 1, + context.getOffsetForCallArg('verify'), + "S501", + "H", + "H" + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/djangoSqlInjection.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/djangoSqlInjection.py Sun Apr 11 18:45:10 2021 +0200 @@ -125,14 +125,16 @@ @param config dictionary with configuration data @type dict """ - if context.isModuleImportedLike('django.db.models'): - if context.callFunctionName == 'RawSQL': - sql = context.node.args[0] - if not AstUtilities.isString(sql): - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S611", - "M", - "M" - ) + if ( + context.isModuleImportedLike('django.db.models') and + context.callFunctionName == 'RawSQL' + ): + sql = context.node.args[0] + if not AstUtilities.isString(sql): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S611", + "M", + "M" + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/flaskDebug.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/flaskDebug.py Sun Apr 11 18:45:10 2021 +0200 @@ -42,13 +42,15 @@ @param config dictionary with configuration data @type dict """ - if context.isModuleImportedLike('flask'): - if context.callFunctionNameQual.endswith('.run'): - if context.checkCallArgValue('debug', 'True'): - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S201", - "L", - "M" - ) + if ( + context.isModuleImportedLike('flask') and + context.callFunctionNameQual.endswith('.run') and + context.checkCallArgValue('debug', 'True') + ): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S201", + "L", + "M" + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalFilePermissions.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalFilePermissions.py Sun Apr 11 18:45:10 2021 +0200 @@ -44,31 +44,33 @@ @param config dictionary with configuration data @type dict """ - if 'chmod' in context.callFunctionName: - if context.callArgsCount == 2: - mode = context.getCallArgAtPosition(1) + if ( + 'chmod' in context.callFunctionName and + context.callArgsCount == 2 + ): + mode = context.getCallArgAtPosition(1) + + if ( + mode is not None and + isinstance(mode, int) and + (mode & stat.S_IWOTH or mode & stat.S_IXGRP) + ): + # world writable is an HIGH, group executable is a MEDIUM + if mode & stat.S_IWOTH: + severity = "H" + else: + severity = "M" - if ( - mode is not None and - isinstance(mode, int) and - (mode & stat.S_IWOTH or mode & stat.S_IXGRP) - ): - # world writable is an HIGH, group executable is a MEDIUM - if mode & stat.S_IWOTH: - severity = "H" - else: - severity = "M" - - filename = context.getCallArgAtPosition(0) - if filename is None: - filename = 'NOT PARSED' - - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S103", - severity, - "H", - oct(mode), - filename - ) + filename = context.getCallArgAtPosition(0) + if filename is None: + filename = 'NOT PARSED' + + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S103", + severity, + "H", + oct(mode), + filename + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalHardcodedPassword.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalHardcodedPassword.py Sun Apr 11 18:45:10 2021 +0200 @@ -96,17 +96,19 @@ elif isinstance(node._securityParent, ast.Compare): # looks for "candidate == 'some_string'" comp = node._securityParent - if isinstance(comp.left, ast.Name): - if RE_CANDIDATES.search(comp.left.id): - if AstUtilities.isString(comp.comparators[0]): - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S105", - "L", - "M", - comp.comparators[0].s - ) + if ( + isinstance(comp.left, ast.Name) and + RE_CANDIDATES.search(comp.left.id) and + AstUtilities.isString(comp.comparators[0]) + ): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S105", + "L", + "M", + comp.comparators[0].s + ) def checkHardcodedPasswordAsFunctionArg(reportError, context, config): @@ -153,13 +155,15 @@ # go through all (param, value)s and look for candidates for key, val in zip(context.node.args.args, defs): - if isinstance(key, (ast.Name, ast.arg)): - if AstUtilities.isString(val) and RE_CANDIDATES.search(key.arg): - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S107", - "L", - "M", - val.s - ) + if ( + isinstance(key, (ast.Name, ast.arg)) and + AstUtilities.isString(val) and RE_CANDIDATES.search(key.arg) + ): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S107", + "L", + "M", + val.s + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/injectionParamiko.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/injectionParamiko.py Sun Apr 11 18:45:10 2021 +0200 @@ -43,12 +43,14 @@ @type dict """ for module in ['paramiko']: - if context.isModuleImportedLike(module): - if context.callFunctionName in ['exec_command']: - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S601", - "M", - "M", - ) + if ( + context.isModuleImportedLike(module) and + context.callFunctionName in ['exec_command'] + ): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S601", + "M", + "M", + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/injectionShell.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/injectionShell.py Sun Apr 11 18:45:10 2021 +0200 @@ -116,25 +116,24 @@ if context.callFunctionNameQual in functionNames: shell, shellValue = hasShell(context) - if shell and shellValue: - if len(context.callArgs) > 0: - sev = _evaluateShellCall(context) - if sev == "L": - reportError( - context.getLinenoForCallArg('shell') - 1, - context.getOffsetForCallArg('shell'), - "S602.L", - sev, - "H", - ) - else: - reportError( - context.getLinenoForCallArg('shell') - 1, - context.getOffsetForCallArg('shell'), - "S602.H", - sev, - "H", - ) + if shell and shellValue and len(context.callArgs) > 0: + sev = _evaluateShellCall(context) + if sev == "L": + reportError( + context.getLinenoForCallArg('shell') - 1, + context.getOffsetForCallArg('shell'), + "S602.L", + sev, + "H", + ) + else: + reportError( + context.getLinenoForCallArg('shell') - 1, + context.getOffsetForCallArg('shell'), + "S602.H", + sev, + "H", + ) def checkSubprocessPopenWithoutShell(reportError, context, config): @@ -153,15 +152,17 @@ else: functionNames = SecurityDefaults["shell_injection_subprocess"] - if context.callFunctionNameQual in functionNames: - if not hasShell(context)[0]: - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S603", - "L", - "H", - ) + if ( + context.callFunctionNameQual in functionNames and + not hasShell(context)[0] + ): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S603", + "L", + "H", + ) def checkOtherFunctionWithShell(reportError, context, config): @@ -208,25 +209,27 @@ else: functionNames = SecurityDefaults["shell_injection_shell"] - if context.callFunctionNameQual in functionNames: - if len(context.callArgs) > 0: - sev = _evaluateShellCall(context) - if sev == "L": - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S605.L", - sev, - "H", - ) - else: - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S605.H", - sev, - "H", - ) + if ( + context.callFunctionNameQual in functionNames and + len(context.callArgs) > 0 + ): + sev = _evaluateShellCall(context) + if sev == "L": + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S605.L", + sev, + "H", + ) + else: + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S605.H", + sev, + "H", + ) def checkStartProcessWithNoShell(reportError, context, config): @@ -281,23 +284,25 @@ else: functionNames += SecurityDefaults["shell_injection_noshell"] - if len(context.callArgs): - if context.callFunctionNameQual in functionNames: - node = context.node.args[0] - - # some calls take an arg list, check the first part - if isinstance(node, ast.List): - node = node.elts[0] - - # make sure the param is a string literal and not a var name - if ( - AstUtilities.isString(node) and - not fullPathMatchRe.match(node.s) - ): - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S607", - "L", - "H", - ) + if ( + len(context.callArgs) and + context.callFunctionNameQual in functionNames + ): + node = context.node.args[0] + + # some calls take an arg list, check the first part + if isinstance(node, ast.List): + node = node.elts[0] + + # make sure the param is a string literal and not a var name + if ( + AstUtilities.isString(node) and + not fullPathMatchRe.match(node.s) + ): + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S607", + "L", + "H", + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/injectionWildcard.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/injectionWildcard.py Sun Apr 11 18:45:10 2021 +0200 @@ -57,36 +57,36 @@ vulnerableFunctions = ['chown', 'chmod', 'tar', 'rsync'] if ( - context.callFunctionNameQual in shellFunctionNames or - (context.callFunctionNameQual in subProcessFunctionNames and - context.checkCallArgValue('shell', 'True')) + (context.callFunctionNameQual in shellFunctionNames or + (context.callFunctionNameQual in subProcessFunctionNames and + context.checkCallArgValue('shell', 'True'))) and + context.callArgsCount >= 1 ): - if context.callArgsCount >= 1: - callArgument = context.getCallArgAtPosition(0) - argumentString = '' - if isinstance(callArgument, list): - for li in callArgument: - argumentString += ' {0}'.format(li) - elif isinstance(callArgument, str): - argumentString = callArgument - - if argumentString != '': - for vulnerableFunction in vulnerableFunctions: - if ( - vulnerableFunction in argumentString and - '*' in argumentString - ): - lineNo = context.getLinenoForCallArg('shell') - if lineNo < 1: - lineNo = context.node.lineno - offset = context.getOffsetForCallArg('shell') - if offset < 0: - offset = context.node.col_offset - reportError( - lineNo - 1, - offset, - "S609", - "H", - "M", - context.callFunctionNameQual - ) + callArgument = context.getCallArgAtPosition(0) + argumentString = '' + if isinstance(callArgument, list): + for li in callArgument: + argumentString += ' {0}'.format(li) + elif isinstance(callArgument, str): + argumentString = callArgument + + if argumentString != '': + for vulnerableFunction in vulnerableFunctions: + if ( + vulnerableFunction in argumentString and + '*' in argumentString + ): + lineNo = context.getLinenoForCallArg('shell') + if lineNo < 1: + lineNo = context.node.lineno + offset = context.getOffsetForCallArg('shell') + if offset < 0: + offset = context.node.col_offset + reportError( + lineNo - 1, + offset, + "S609", + "H", + "M", + context.callFunctionNameQual + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/insecureSslTls.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/insecureSslTls.py Sun Apr 11 18:45:10 2021 +0200 @@ -138,16 +138,18 @@ @param config dictionary with configuration data @type dict """ - if context.callFunctionNameQual == 'ssl.wrap_socket': - if context.checkCallArgValue('ssl_version') is None: - # checkCallArgValue() returns False if the argument is found - # but does not match the supplied value (or the default None). - # It returns None if the argument passed doesn't exist. This - # tests for that (ssl_version is not specified). - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S504", - "L", - "M", - ) + if ( + context.callFunctionNameQual == 'ssl.wrap_socket' and + context.checkCallArgValue('ssl_version') is None + ): + # checkCallArgValue() returns False if the argument is found + # but does not match the supplied value (or the default None). + # It returns None if the argument passed doesn't exist. This + # tests for that (ssl_version is not specified). + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S504", + "L", + "M", + )
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/sshNoHostKeyVerification.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/sshNoHostKeyVerification.py Sun Apr 11 18:45:10 2021 +0200 @@ -44,16 +44,14 @@ """ if ( context.isModuleImportedLike('paramiko') and - context.callFunctionName == 'set_missing_host_key_policy' + context.callFunctionName == 'set_missing_host_key_policy' and + context.callArgs and + context.callArgs[0] in ['AutoAddPolicy', 'WarningPolicy'] ): - if ( - context.callArgs and - context.callArgs[0] in ['AutoAddPolicy', 'WarningPolicy'] - ): - reportError( - context.node.lineno - 1, - context.node.col_offset, - "S507", - "H", - "M", - ) + reportError( + context.node.lineno - 1, + context.node.col_offset, + "S507", + "H", + "M", + )
--- a/eric6/Plugins/PluginCodeStyleChecker.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/PluginCodeStyleChecker.py Sun Apr 11 18:45:10 2021 +0200 @@ -292,10 +292,9 @@ if menu: menu.removeAction(self.__projectAct) - if self.__projectBrowserMenu: - if self.__projectBrowserAct: - self.__projectBrowserMenu.removeAction( - self.__projectBrowserAct) + if self.__projectBrowserMenu and self.__projectBrowserAct: + self.__projectBrowserMenu.removeAction( + self.__projectBrowserAct) for editor in self.__editors: editor.showMenu.disconnect(self.__editorShowMenu) @@ -443,16 +442,19 @@ of the editors. """ editor = e5App().getObject("ViewManager").activeWindow() - if editor is not None: - if editor.checkDirty() and editor.getFileName() is not None: - from CheckerPlugins.CodeStyleChecker import ( - CodeStyleCheckerDialog - ) - self.__editorCodeStyleCheckerDialog = ( - CodeStyleCheckerDialog.CodeStyleCheckerDialog(self) - ) - self.__editorCodeStyleCheckerDialog.show() - self.__editorCodeStyleCheckerDialog.start( - editor.getFileName(), - save=True, - repeat=True) + if ( + editor is not None and + editor.checkDirty() and + editor.getFileName() is not None + ): + from CheckerPlugins.CodeStyleChecker import ( + CodeStyleCheckerDialog + ) + self.__editorCodeStyleCheckerDialog = ( + CodeStyleCheckerDialog.CodeStyleCheckerDialog(self) + ) + self.__editorCodeStyleCheckerDialog.show() + self.__editorCodeStyleCheckerDialog.start( + editor.getFileName(), + save=True, + repeat=True)
--- a/eric6/Plugins/PluginEricapi.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/PluginEricapi.py Sun Apr 11 18:45:10 2021 +0200 @@ -138,11 +138,10 @@ @param menuName name of the menu to be shown (string) @param menu reference to the menu (QMenu) """ - if menuName == "Apidoc": - if self.__projectAct is not None: - self.__projectAct.setEnabled( - e5App().getObject("Project").getProjectLanguage() in - ["Python", "Python3", "Ruby", "MicroPython"]) + if menuName == "Apidoc" and self.__projectAct is not None: + self.__projectAct.setEnabled( + e5App().getObject("Project").getProjectLanguage() in + ["Python", "Python3", "Ruby", "MicroPython"]) def __doEricapi(self): """
--- a/eric6/Plugins/PluginEricdoc.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/PluginEricdoc.py Sun Apr 11 18:45:10 2021 +0200 @@ -159,11 +159,10 @@ @param menuName name of the menu to be shown (string) @param menu reference to the menu (QMenu) """ - if menuName == "Apidoc": - if self.__projectAct is not None: - self.__projectAct.setEnabled( - e5App().getObject("Project").getProjectLanguage() in - ["Python", "Python3", "Ruby", "MicroPython"]) + if menuName == "Apidoc" and self.__projectAct is not None: + self.__projectAct.setEnabled( + e5App().getObject("Project").getProjectLanguage() in + ["Python", "Python3", "Ruby", "MicroPython"]) def __doEricdoc(self): """
--- a/eric6/Plugins/PluginSyntaxChecker.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/PluginSyntaxChecker.py Sun Apr 11 18:45:10 2021 +0200 @@ -224,10 +224,9 @@ if menu: menu.removeAction(self.__projectAct) - if self.__projectBrowserMenu: - if self.__projectBrowserAct: - self.__projectBrowserMenu.removeAction( - self.__projectBrowserAct) + if self.__projectBrowserMenu and self.__projectBrowserAct: + self.__projectBrowserMenu.removeAction( + self.__projectBrowserAct) for editor in self.__editors: editor.showMenu.disconnect(self.__editorShowMenu)
--- a/eric6/Plugins/VcsPlugins/vcsGit/git.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/git.py Sun Apr 11 18:45:10 2021 +0200 @@ -1106,18 +1106,17 @@ path = line[3:].split(" -> ")[-1] name = os.path.normcase(os.path.join(repodir, path)) dirName = os.path.dirname(name) - if name.startswith(dname): - if flag in "?!": - isDir = name.endswith(("/", "\\")) - if isDir: - name = name[:-1] - if name in names: - names[name] = self.canBeAdded - if isDir: - # it's a directory - for nname in names: - if nname.startswith(name): - names[nname] = self.canBeAdded + if name.startswith(dname) and flag in "?!": + isDir = name.endswith(("/", "\\")) + if isDir: + name = name[:-1] + if name in names: + names[name] = self.canBeAdded + if isDir: + # it's a directory + for nname in names: + if nname.startswith(name): + names[nname] = self.canBeAdded if flag not in "?!": self.statusCache[name] = self.canBeCommitted self.statusCache[dirName] = self.canBeCommitted
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -1268,35 +1268,34 @@ self.__resizeColumnsLog() - if self.__started: - if not self.__finishCallbacks: - # we are really done - if self.__selectedRevisions: - foundItems = self.logTree.findItems( - self.__selectedRevisions[0], Qt.MatchFlag.MatchExactly, + if self.__started and not self.__finishCallbacks: + # we are really done + if self.__selectedRevisions: + foundItems = self.logTree.findItems( + self.__selectedRevisions[0], Qt.MatchFlag.MatchExactly, + self.RevisionColumn) + if foundItems: + self.logTree.setCurrentItem(foundItems[0]) + else: + self.logTree.setCurrentItem( + self.logTree.topLevelItem(0)) + elif self.__projectWorkingDirParents: + for rev in self.__projectWorkingDirParents: + # rev string format must match with the format of the + # __generateLogItem() method + items = self.logTree.findItems( + "{0:>7}:".format(rev), + Qt.MatchFlag.MatchStartsWith, self.RevisionColumn) - if foundItems: - self.logTree.setCurrentItem(foundItems[0]) - else: - self.logTree.setCurrentItem( - self.logTree.topLevelItem(0)) - elif self.__projectWorkingDirParents: - for rev in self.__projectWorkingDirParents: - # rev string format must match with the format of the - # __generateLogItem() method - items = self.logTree.findItems( - "{0:>7}:".format(rev), - Qt.MatchFlag.MatchStartsWith, - self.RevisionColumn) - if items: - self.logTree.setCurrentItem(items[0]) - break - else: - self.logTree.setCurrentItem( - self.logTree.topLevelItem(0)) + if items: + self.logTree.setCurrentItem(items[0]) + break else: - self.logTree.setCurrentItem(self.logTree.topLevelItem(0)) - self.__started = False + self.logTree.setCurrentItem( + self.logTree.topLevelItem(0)) + else: + self.logTree.setCurrentItem(self.logTree.topLevelItem(0)) + self.__started = False if self.commandMode in ("incoming", "outgoing"): self.commandMode = "log" # switch to log mode
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Sun Apr 11 18:45:10 2021 +0200 @@ -826,10 +826,13 @@ msgPart = "global " if tagOp in [HgTagDialog.DeleteGlobalTag, HgTagDialog.DeleteLocalTag]: args.append('--remove') - if tagOp in [HgTagDialog.CreateGlobalTag, HgTagDialog.CreateLocalTag]: - if revision: - args.append("--rev") - args.append(revision) + if ( + tagOp in [ + HgTagDialog.CreateGlobalTag, HgTagDialog.CreateLocalTag] and + revision + ): + args.append("--rev") + args.append(revision) if force: args.append("--force") args.append('--message') @@ -1078,18 +1081,17 @@ flag, path = line.split(" ", 1) name = os.path.normcase(os.path.join(repoPath, path)) dirName = os.path.dirname(name) - if name.startswith(dname): - if flag not in "?I": - if name in names: - names[name] = self.canBeCommitted - if dirName in names: - names[dirName] = self.canBeCommitted - if dirs: - for d in dirs: - if name.startswith(d): - names[d] = self.canBeCommitted - dirs.remove(d) - break + if name.startswith(dname) and flag not in "?I": + if name in names: + names[name] = self.canBeCommitted + if dirName in names: + names[dirName] = self.canBeCommitted + if dirs: + for d in dirs: + if name.startswith(d): + names[d] = self.canBeCommitted + dirs.remove(d) + break if flag not in "?I": self.statusCache[name] = self.canBeCommitted self.statusCache[dirName] = self.canBeCommitted
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/SvnDiffDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/SvnDiffDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -261,10 +261,12 @@ self.__appendText( "{0}{1}".format(line, os.linesep)) - if counter % 30 == 0: + if ( + counter % 30 == 0 and + self._clientCancelCallback() + ): # check for cancel every 30 lines - if self._clientCancelCallback(): - break + break if self._clientCancelCallback(): break except pysvn.ClientError as e:
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/SvnPropListDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/SvnPropListDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -128,10 +128,12 @@ for propName, propVal in list(prop.items()): self.__generateItem(path, propName, propVal) self.propsFound = True - if counter % 30 == 0: + if ( + counter % 30 == 0 and + self._clientCancelCallback() + ): # check for cancel every 30 items - if self._clientCancelCallback(): - break + break if self._clientCancelCallback(): break except pysvn.ClientError as e:
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/SvnStatusDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/SvnStatusDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -439,10 +439,12 @@ file.entry.commit_author if file.entry else "", file.path ) - if counter % 30 == 0: + if ( + counter % 30 == 0 and + self._clientCancelCallback() + ): # check for cancel every 30 items - if self._clientCancelCallback(): - break + break if self._clientCancelCallback(): break except pysvn.ClientError as e:
--- a/eric6/Plugins/VcsPlugins/vcsSubversion/SvnLogBrowserDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsSubversion/SvnLogBrowserDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -430,28 +430,27 @@ "copyfrom_revision": "", }) elif ( - match.re is self.rx_sep1 or - match.re is self.rx_sep2 + (match.re is self.rx_sep1 or match.re is self.rx_sep2) and + len(log) > 1 ): - if len(log) > 1: - self.__generateLogItem( - log["author"], log["date"], log["message"], - log["revision"], changedPaths) - dt = QDate.fromString(log["date"], Qt.DateFormat.ISODate) - if ( - not self.__maxDate.isValid() and - not self.__minDate.isValid() - ): + self.__generateLogItem( + log["author"], log["date"], log["message"], + log["revision"], changedPaths) + dt = QDate.fromString(log["date"], Qt.DateFormat.ISODate) + if ( + not self.__maxDate.isValid() and + not self.__minDate.isValid() + ): + self.__maxDate = dt + self.__minDate = dt + else: + if self.__maxDate < dt: self.__maxDate = dt + if self.__minDate > dt: self.__minDate = dt - else: - if self.__maxDate < dt: - self.__maxDate = dt - if self.__minDate > dt: - self.__minDate = dt - noEntries += 1 - log = {"message": []} - changedPaths = [] + noEntries += 1 + log = {"message": []} + changedPaths = [] self.__resizeColumnsLog() self.__resortLog()
--- a/eric6/Plugins/WizardPlugins/DotDesktopWizard/DotDesktopWizardDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Plugins/WizardPlugins/DotDesktopWizard/DotDesktopWizardDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -190,10 +190,12 @@ code.append('X-KDE-PluginInfo-EnabledByDefault=true') # step 2b: Unity entries - if self.typeComboBox.currentIndex() == 2: - if self.unityShortcutsEdit.text(): - code.append('X-Ayatana-Desktop-Shortcuts=' + - self.unityShortcutsEdit.text()) + if ( + self.typeComboBox.currentIndex() == 2 and + self.unityShortcutsEdit.text() + ): + code.append('X-Ayatana-Desktop-Shortcuts=' + + self.unityShortcutsEdit.text()) # step 3: action entries actions = [act for act in self.actionsEdit.text().split(";") if act]
--- a/eric6/Preferences/ConfigurationPages/EditorFilePage.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Preferences/ConfigurationPages/EditorFilePage.py Sun Apr 11 18:45:10 2021 +0200 @@ -298,11 +298,10 @@ self.tr("Add File Filter"), self.tr("Enter the file filter entry:"), QLineEdit.EchoMode.Normal) - if ok and fileFilter: - if self.__checkFileFilter(fileFilter): - self.fileFiltersList.addItem(fileFilter) - self.__extractFileFilters() - self.__setDefaultFiltersLists(keepSelection=True) + if ok and fileFilter and self.__checkFileFilter(fileFilter): + self.fileFiltersList.addItem(fileFilter) + self.__extractFileFilters() + self.__setDefaultFiltersLists(keepSelection=True) @pyqtSlot() def on_editFileFilterButton_clicked(self): @@ -316,11 +315,10 @@ self.tr("Enter the file filter entry:"), QLineEdit.EchoMode.Normal, fileFilter) - if ok and fileFilter: - if self.__checkFileFilter(fileFilter): - self.fileFiltersList.currentItem().setText(fileFilter) - self.__extractFileFilters() - self.__setDefaultFiltersLists(keepSelection=True) + if ok and fileFilter and self.__checkFileFilter(fileFilter): + self.fileFiltersList.currentItem().setText(fileFilter) + self.__extractFileFilters() + self.__setDefaultFiltersLists(keepSelection=True) @pyqtSlot() def on_deleteFileFilterButton_clicked(self):
--- a/eric6/Preferences/ConfigurationPages/MasterPasswordEntryDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Preferences/ConfigurationPages/MasterPasswordEntryDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -61,11 +61,13 @@ enable = False error = error or self.tr("Repeated password is wrong.") - if self.currentPasswordEdit.isEnabled(): - if self.newPasswordEdit.text() == self.currentPasswordEdit.text(): - enable = False - error = error or self.tr( - "Old and new password must not be the same.") + if ( + self.currentPasswordEdit.isEnabled() and + self.newPasswordEdit.text() == self.currentPasswordEdit.text() + ): + enable = False + error = error or self.tr( + "Old and new password must not be the same.") self.buttonBox.button( QDialogButtonBox.StandardButton.Ok).setEnabled(enable)
--- a/eric6/Preferences/ToolConfigurationDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Preferences/ToolConfigurationDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -266,14 +266,13 @@ @param path path of the executable @type str """ - if path: - if not Utilities.isinpath(path): - E5MessageBox.critical( - self, - self.tr("Select executable"), - self.tr( - "The selected file is not an executable." - " Please choose an executable filename.")) + if path and not Utilities.isinpath(path): + E5MessageBox.critical( + self, + self.tr("Select executable"), + self.tr( + "The selected file is not an executable." + " Please choose an executable filename.")) def on_toolsList_currentRowChanged(self, row): """
--- a/eric6/Project/CreateDialogCodeDialog.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Project/CreateDialogCodeDialog.py Sun Apr 11 18:45:10 2021 +0200 @@ -339,19 +339,19 @@ itm2 = QStandardItem(methodDict["signature"]) itm.appendRow(itm2) - if self.__module is not None: - if ( - methodDict["methods"][0] in signatureList or - methodDict["methods"][1] in signatureList - ): - itm2.setFlags( - Qt.ItemFlags(Qt.ItemFlag.ItemIsEnabled)) - itm2.setCheckState(Qt.CheckState.Checked) - if e5App().usesDarkPalette(): - itm2.setForeground(QBrush(QColor("#75bfff"))) - else: - itm2.setForeground(QBrush(Qt.GlobalColor.blue)) - continue + if ( + self.__module is not None and + (methodDict["methods"][0] in signatureList or + methodDict["methods"][1] in signatureList) + ): + itm2.setFlags( + Qt.ItemFlags(Qt.ItemFlag.ItemIsEnabled)) + itm2.setCheckState(Qt.CheckState.Checked) + if e5App().usesDarkPalette(): + itm2.setForeground(QBrush(QColor("#75bfff"))) + else: + itm2.setForeground(QBrush(Qt.GlobalColor.blue)) + continue itm2.setData(methodDict["pyqt_signature"], pyqtSignatureRole)
--- a/eric6/Project/Project.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Project/Project.py Sun Apr 11 18:45:10 2021 +0200 @@ -2960,154 +2960,153 @@ QApplication.processEvents() - if fn: - if self.closeProject(): + if fn and self.closeProject(): + with E5OverrideCursor(): + ok = self.__readProject(fn) + if ok: + self.opened = True + if not self.pdata["FILETYPES"]: + self.initFileTypes() + else: + self.updateFileTypes() + + try: + # create management directory if not present + self.createProjectManagementDir() + except OSError: + E5MessageBox.critical( + self.ui, + self.tr("Create project management directory"), + self.tr( + "<p>The project directory <b>{0}</b> is not" + " writable.</p>") + .format(self.ppath)) + return + + # read a user specific project file + self.__readUserProperties() + with E5OverrideCursor(): - ok = self.__readProject(fn) - if ok: - self.opened = True - if not self.pdata["FILETYPES"]: - self.initFileTypes() - else: - self.updateFileTypes() - - try: - # create management directory if not present - self.createProjectManagementDir() - except OSError: - E5MessageBox.critical( - self.ui, - self.tr("Create project management directory"), - self.tr( - "<p>The project directory <b>{0}</b> is not" - " writable.</p>") - .format(self.ppath)) - return - - # read a user specific project file - self.__readUserProperties() - - with E5OverrideCursor(): - oldState = self.isDirty() - self.vcs = self.initVCS() - if self.vcs is None and self.isDirty() == oldState: - # check, if project is version controlled - pluginManager = e5App().getObject("PluginManager") - for indicator, vcsData in ( - pluginManager.getVcsSystemIndicators().items() - ): - if os.path.exists( - os.path.join(self.ppath, indicator)): - if len(vcsData) > 1: - vcsList = [] + oldState = self.isDirty() + self.vcs = self.initVCS() + if self.vcs is None and self.isDirty() == oldState: + # check, if project is version controlled + pluginManager = e5App().getObject("PluginManager") + for indicator, vcsData in ( + pluginManager.getVcsSystemIndicators().items() + ): + if os.path.exists( + os.path.join(self.ppath, indicator)): + if len(vcsData) > 1: + vcsList = [] + for ( + _vcsSystemStr, vcsSystemDisplay + ) in vcsData: + vcsList.append(vcsSystemDisplay) + with E5OverridenCursor(): + res, vcs_ok = QInputDialog.getItem( + None, + self.tr("New Project"), + self.tr( + "Select Version Control" + " System"), + vcsList, + 0, False) + if vcs_ok: for ( - _vcsSystemStr, vcsSystemDisplay + vcsSystemStr, vcsSystemDisplay ) in vcsData: - vcsList.append(vcsSystemDisplay) - with E5OverridenCursor(): - res, vcs_ok = QInputDialog.getItem( - None, - self.tr("New Project"), - self.tr( - "Select Version Control" - " System"), - vcsList, - 0, False) - if vcs_ok: - for ( - vcsSystemStr, vcsSystemDisplay - ) in vcsData: - if res == vcsSystemDisplay: - vcsSystem = vcsSystemStr - break - else: - vcsSystem = "None" + if res == vcsSystemDisplay: + vcsSystem = vcsSystemStr + break else: vcsSystem = "None" else: - vcsSystem = vcsData[0][0] - self.pdata["VCS"] = vcsSystem - self.vcs = self.initVCS() - self.setDirty(True) - if ( - self.vcs is not None and - (self.vcs.vcsRegisteredState(self.ppath) != - self.vcs.canBeCommitted) - ): - self.pdata["VCS"] = 'None' - self.vcs = self.initVCS() - self.closeAct.setEnabled(True) - self.saveasAct.setEnabled(True) - self.actGrp2.setEnabled(True) - self.propsAct.setEnabled(True) - self.userPropsAct.setEnabled(True) - self.filetypesAct.setEnabled(True) - self.lexersAct.setEnabled(True) - self.sessActGrp.setEnabled(True) - self.dbgActGrp.setEnabled(True) - self.menuDebuggerAct.setEnabled(True) - self.menuSessionAct.setEnabled(True) - self.menuCheckAct.setEnabled(True) - self.menuShowAct.setEnabled(True) - self.menuDiagramAct.setEnabled(True) - self.menuApidocAct.setEnabled(True) - self.menuPackagersAct.setEnabled(True) - self.pluginGrp.setEnabled( - self.pdata["PROJECTTYPE"] in ["E6Plugin"]) - self.addLanguageAct.setEnabled( - bool(self.pdata["TRANSLATIONPATTERN"])) - self.makeGrp.setEnabled( - self.pdata["MAKEPARAMS"]["MakeEnabled"]) - self.menuMakeAct.setEnabled( - self.pdata["MAKEPARAMS"]["MakeEnabled"]) - - # open a project debugger properties file being quiet - # about errors - if Preferences.getProject("AutoLoadDbgProperties"): - self.__readDebugProperties(True) - - self.__model.projectOpened() - self.projectOpenedHooks.emit() - self.projectOpened.emit() + vcsSystem = "None" + else: + vcsSystem = vcsData[0][0] + self.pdata["VCS"] = vcsSystem + self.vcs = self.initVCS() + self.setDirty(True) + if ( + self.vcs is not None and + (self.vcs.vcsRegisteredState(self.ppath) != + self.vcs.canBeCommitted) + ): + self.pdata["VCS"] = 'None' + self.vcs = self.initVCS() + self.closeAct.setEnabled(True) + self.saveasAct.setEnabled(True) + self.actGrp2.setEnabled(True) + self.propsAct.setEnabled(True) + self.userPropsAct.setEnabled(True) + self.filetypesAct.setEnabled(True) + self.lexersAct.setEnabled(True) + self.sessActGrp.setEnabled(True) + self.dbgActGrp.setEnabled(True) + self.menuDebuggerAct.setEnabled(True) + self.menuSessionAct.setEnabled(True) + self.menuCheckAct.setEnabled(True) + self.menuShowAct.setEnabled(True) + self.menuDiagramAct.setEnabled(True) + self.menuApidocAct.setEnabled(True) + self.menuPackagersAct.setEnabled(True) + self.pluginGrp.setEnabled( + self.pdata["PROJECTTYPE"] in ["E6Plugin"]) + self.addLanguageAct.setEnabled( + bool(self.pdata["TRANSLATIONPATTERN"])) + self.makeGrp.setEnabled( + self.pdata["MAKEPARAMS"]["MakeEnabled"]) + self.menuMakeAct.setEnabled( + self.pdata["MAKEPARAMS"]["MakeEnabled"]) + + # open a project debugger properties file being quiet + # about errors + if Preferences.getProject("AutoLoadDbgProperties"): + self.__readDebugProperties(True) - if Preferences.getProject("SearchNewFiles"): - self.__doSearchNewFiles() - - # read a project tasks file - self.__readTasks() - self.ui.taskViewer.setProjectOpen(True) - # rescan project tasks - if Preferences.getProject("TasksProjectRescanOnOpen"): - e5App().getObject("TaskViewer" - ).regenerateProjectTasks(quiet=True) + self.__model.projectOpened() + self.projectOpenedHooks.emit() + self.projectOpened.emit() + + if Preferences.getProject("SearchNewFiles"): + self.__doSearchNewFiles() + + # read a project tasks file + self.__readTasks() + self.ui.taskViewer.setProjectOpen(True) + # rescan project tasks + if Preferences.getProject("TasksProjectRescanOnOpen"): + e5App().getObject("TaskViewer" + ).regenerateProjectTasks(quiet=True) + + if restoreSession: + # open the main script + if self.pdata["MAINSCRIPT"]: + if not os.path.isabs(self.pdata["MAINSCRIPT"]): + ms = os.path.join( + self.ppath, self.pdata["MAINSCRIPT"]) + else: + ms = self.pdata["MAINSCRIPT"] + self.sourceFile.emit(ms) - if restoreSession: - # open the main script - if self.pdata["MAINSCRIPT"]: - if not os.path.isabs(self.pdata["MAINSCRIPT"]): - ms = os.path.join( - self.ppath, self.pdata["MAINSCRIPT"]) - else: - ms = self.pdata["MAINSCRIPT"] - self.sourceFile.emit(ms) - - # open a project session file being quiet about errors - if reopen: - self.__readSession(quiet=True, indicator="_tmp") - elif Preferences.getProject("AutoLoadSession"): - self.__readSession(quiet=True) - - # start the VCS monitor thread - if self.vcs is not None: - self.vcs.startStatusMonitor(self) - self.vcs.vcsStatusMonitorData.connect( - self.__model.changeVCSStates) - self.vcs.vcsStatusMonitorStatus.connect( - self.__statusMonitorStatus) - self.vcs.vcsStatusMonitorInfo.connect( - self.vcsStatusMonitorInfo) - self.vcs.vcsStatusChanged.connect( - self.__vcsStatusChanged) + # open a project session file being quiet about errors + if reopen: + self.__readSession(quiet=True, indicator="_tmp") + elif Preferences.getProject("AutoLoadSession"): + self.__readSession(quiet=True) + + # start the VCS monitor thread + if self.vcs is not None: + self.vcs.startStatusMonitor(self) + self.vcs.vcsStatusMonitorData.connect( + self.__model.changeVCSStates) + self.vcs.vcsStatusMonitorStatus.connect( + self.__statusMonitorStatus) + self.vcs.vcsStatusMonitorInfo.connect( + self.vcsStatusMonitorInfo) + self.vcs.vcsStatusChanged.connect( + self.__vcsStatusChanged) def reopenProject(self): """ @@ -3799,19 +3798,23 @@ newfn = self.getRelativePath(newfn) if newfn in self.pdata[group]: return True - elif group == "OTHERS": - if any(newfn.startswith(entry) for entry in self.pdata[group]): - return True + elif ( + group == "OTHERS" and + any(newfn.startswith(entry) for entry in self.pdata[group]) + ): + return True if Utilities.isWindowsPlatform(): # try the above case-insensitive newfn = newfn.lower() if any(entry.lower() == newfn for entry in self.pdata[group]): return True - elif group == "OTHERS": - if any(newfn.startswith(entry.lower()) - for entry in self.pdata[group]): - return True + elif ( + group == "OTHERS" and + any(newfn.startswith(entry.lower()) + for entry in self.pdata[group]) + ): + return True return False @@ -4728,16 +4731,14 @@ newFiles.append(ns) elif ( filetype == "TRANSLATIONS" and - fn not in self.pdata["TRANSLATIONS"] + fn not in self.pdata["TRANSLATIONS"] and + (fnmatch.fnmatch(ns, pattern) or + fnmatch.fnmatch(ns, binpattern)) ): - if ( - fnmatch.fnmatch(ns, pattern) or - fnmatch.fnmatch(ns, binpattern) - ): - if autoInclude and AI: - self.appendFile(ns) - else: - newFiles.append(ns) + if autoInclude and AI: + self.appendFile(ns) + else: + newFiles.append(ns) # if autoInclude is set there is no more work left if (autoInclude and AI): @@ -4858,13 +4859,15 @@ else: forProject = False - if forProject and self.pdata["VCS"] and self.pdata["VCS"] != 'None': - if ( - self.pudata["VCSOVERRIDE"] and - not nooverride - ): - vcsSystem = self.pudata["VCSOVERRIDE"] - override = True + if ( + forProject and + self.pdata["VCS"] and + self.pdata["VCS"] != 'None' and + self.pudata["VCSOVERRIDE"] and + not nooverride + ): + vcsSystem = self.pudata["VCSOVERRIDE"] + override = True if vcsSystem is not None: import VCS
--- a/eric6/Project/ProjectBrowserModel.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Project/ProjectBrowserModel.py Sun Apr 11 18:45:10 2021 +0200 @@ -169,9 +169,11 @@ @param order sort order (Qt.SortOrder) (for special sorting) @return true, if this item is less than other (boolean) """ - if issubclass(other.__class__, BrowserFileItem): - if Preferences.getUI("BrowsersListFoldersFirst"): - return order == Qt.SortOrder.AscendingOrder + if ( + issubclass(other.__class__, BrowserFileItem) and + Preferences.getUI("BrowsersListFoldersFirst") + ): + return order == Qt.SortOrder.AscendingOrder return BrowserItem.lessThan(self, other, column, order)
--- a/eric6/Project/ProjectOthersBrowser.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Project/ProjectOthersBrowser.py Sun Apr 11 18:45:10 2021 +0200 @@ -226,9 +226,11 @@ itmList = self.getSelectedItems() for itm in itmList: - if isinstance(itm, ProjectBrowserFileItem): - if itm.isPixmapFile(): - self.pixmapEditFile.emit(itm.fileName()) + if ( + isinstance(itm, ProjectBrowserFileItem) and + itm.isPixmapFile() + ): + self.pixmapEditFile.emit(itm.fileName()) def _openHexEditor(self): """
--- a/eric6/Project/ProjectTranslationsBrowser.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/Project/ProjectTranslationsBrowser.py Sun Apr 11 18:45:10 2021 +0200 @@ -711,10 +711,12 @@ dname = self.project.getRelativePath(itm.dirName()) trfiles = sorted(self.project.pdata["TRANSLATIONS"][:]) for trfile in trfiles: - if trfile.startswith(dname): - if trfile not in fileNames: - fileNames.append( - os.path.join(self.project.ppath, trfile)) + if ( + trfile.startswith(dname) and + trfile not in fileNames + ): + fileNames.append( + os.path.join(self.project.ppath, trfile)) else: fn = itm.fileName() if fn not in fileNames:
--- a/eric6/QScintilla/DocstringGenerator/PyDocstringGenerator.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/DocstringGenerator/PyDocstringGenerator.py Sun Apr 11 18:45:10 2021 +0200 @@ -757,9 +757,11 @@ for line in lineList: line = line.strip() - if returnFound is False: - if re.match(returnPattern, line): - returnFound = True + if ( + returnFound is False and + re.match(returnPattern, line) + ): + returnFound = True if returnFound: returnTmpLine += line
--- a/eric6/QScintilla/Editor.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/Editor.py Sun Apr 11 18:45:10 2021 +0200 @@ -2165,13 +2165,13 @@ if self.filetype == "JavaScript": return True - if self.filetype == "": - if ( - self.fileName and - os.path.splitext(self.fileName)[1] == ".js" - ): - self.filetype = "JavaScript" - return True + if ( + self.filetype == "" and + self.fileName and + os.path.splitext(self.fileName)[1] == ".js" + ): + self.filetype = "JavaScript" + return True return False @@ -2248,25 +2248,25 @@ """ if ( mtype & (self.SC_MOD_INSERTTEXT | self.SC_MOD_DELETETEXT) and - linesAdded != 0 + linesAdded != 0 and + self.breaks ): - if self.breaks: - bps = [] # list of breakpoints - for handle, (ln, cond, temp, enabled, ignorecount) in ( - self.breaks.items() - ): - line = self.markerLine(handle) + 1 - if ln != line: - bps.append((ln, line)) - self.breaks[handle] = (line, cond, temp, enabled, - ignorecount) - self.inLinesChanged = True - for ln, line in sorted(bps, reverse=linesAdded > 0): - index1 = self.breakpointModel.getBreakPointIndex( - self.fileName, ln) - index2 = self.breakpointModel.index(index1.row(), 1) - self.breakpointModel.setData(index2, line) - self.inLinesChanged = False + bps = [] # list of breakpoints + for handle, (ln, cond, temp, enabled, ignorecount) in ( + self.breaks.items() + ): + line = self.markerLine(handle) + 1 + if ln != line: + bps.append((ln, line)) + self.breaks[handle] = (line, cond, temp, enabled, + ignorecount) + self.inLinesChanged = True + for ln, line in sorted(bps, reverse=linesAdded > 0): + index1 = self.breakpointModel.getBreakPointIndex( + self.fileName, ln) + index2 = self.breakpointModel.index(index1.row(), 1) + self.breakpointModel.setData(index2, line) + self.inLinesChanged = False def __restoreBreakpoints(self): """ @@ -3362,13 +3362,13 @@ return False res = self.writeFile(fn) - if res: + if ( + res and + self.project.isOpen() and + self.project.startswithProjectPath(fn) + ): # save to project, if a project is loaded - if ( - self.project.isOpen() and - self.project.startswithProjectPath(fn) - ): - self.project.appendFile(fn) + self.project.appendFile(fn) return res @@ -7060,11 +7060,13 @@ # See it is text to insert. if len(txt) and txt >= " ": - if self.hasSelectedText(): - if txt in Editor.EncloseChars: - encloseSelectedText(Editor.EncloseChars[txt]) - ev.accept() - return + if ( + self.hasSelectedText() and + txt in Editor.EncloseChars + ): + encloseSelectedText(Editor.EncloseChars[txt]) + ev.accept() + return super().keyPressEvent(ev) else:
--- a/eric6/QScintilla/EditorOutlineModel.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/EditorOutlineModel.py Sun Apr 11 18:45:10 2021 +0200 @@ -243,9 +243,11 @@ elif hasattr(child, "linenos"): if lineno in child.linenos(): return child - elif hasattr(child, "lineno"): - if lineno == child.lineno(): - return child + elif ( + hasattr(child, "lineno") and + lineno == child.lineno() + ): + return child else: return None
--- a/eric6/QScintilla/MiniEditor.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/MiniEditor.py Sun Apr 11 18:45:10 2021 +0200 @@ -129,11 +129,13 @@ # See it is text to insert. if len(txt) and txt >= " ": - if self.hasSelectedText(): - if txt in MiniScintilla.EncloseChars: - encloseSelectedText(MiniScintilla.EncloseChars[txt]) - ev.accept() - return + if ( + self.hasSelectedText() and + txt in MiniScintilla.EncloseChars + ): + encloseSelectedText(MiniScintilla.EncloseChars[txt]) + ev.accept() + return super().keyPressEvent(ev) else:
--- a/eric6/QScintilla/Shell.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/Shell.py Sun Apr 11 18:45:10 2021 +0200 @@ -892,26 +892,26 @@ if ( not self.__windowed and - Preferences.getDebugger("ShowExceptionInShell") + Preferences.getDebugger("ShowExceptionInShell") and + exceptionType ): - if exceptionType: - if stackTrace: - self.__write( - self.tr('Exception "{0}"\n{1}\nFile: {2}, Line: {3}\n') - .format( - exceptionType, - exceptionMessage, - stackTrace[0][0], - stackTrace[0][1] - ) + if stackTrace: + self.__write( + self.tr('Exception "{0}"\n{1}\nFile: {2}, Line: {3}\n') + .format( + exceptionType, + exceptionMessage, + stackTrace[0][0], + stackTrace[0][1] ) - else: - self.__write( - self.tr('Exception "{0}"\n{1}\n') - .format( - exceptionType, - exceptionMessage) - ) + ) + else: + self.__write( + self.tr('Exception "{0}"\n{1}\n') + .format( + exceptionType, + exceptionMessage) + ) def __clientSyntaxError(self, message, filename, lineNo, characterNo): """
--- a/eric6/QScintilla/TypingCompleters/CompleterPython.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/TypingCompleters/CompleterPython.py Sun Apr 11 18:45:10 2021 +0200 @@ -143,10 +143,9 @@ # skip matching closing parenthesis elif char in [')', '}', ']']: txt = self.editor.text(line) - if col < len(txt) and char == txt[col]: - if self.__skipBrace: - self.editor.setSelection(line, col, line, col + 1) - self.editor.removeSelectedText() + if col < len(txt) and char == txt[col] and self.__skipBrace: + self.editor.setSelection(line, col, line, col + 1) + self.editor.removeSelectedText() # space # insert import, dedent to if for elif, dedent to try for except, @@ -171,34 +170,29 @@ # comma # insert blank - elif char == ',': - if self.__insertBlank: - self.editor.insert(' ') - self.editor.setCursorPosition(line, col + 1) + elif char == ',' and self.__insertBlank: + self.editor.insert(' ') + self.editor.setCursorPosition(line, col + 1) # open curly brace # insert closing brace - elif char == '{': - if self.__insertClosingBrace: - self.editor.insert('}') + elif char == '{' and self.__insertClosingBrace: + self.editor.insert('}') # open bracket # insert closing bracket - elif char == '[': - if self.__insertClosingBrace: - self.editor.insert(']') + elif char == '[' and self.__insertClosingBrace: + self.editor.insert(']') # double quote # insert double quote - elif char == '"': - if self.__insertQuote: - self.editor.insert('"') + elif char == '"' and self.__insertQuote: + self.editor.insert('"') # quote # insert quote - elif char == '\'': - if self.__insertQuote: - self.editor.insert('\'') + elif char == '\'' and self.__insertQuote: + self.editor.insert('\'') # colon # skip colon, dedent to if for else: @@ -219,37 +213,36 @@ # new line # indent to opening brace - elif char == '\n': - if self.__indentBrace: - txt = self.editor.text(line - 1) - if re.search(":\r?\n", txt) is None: - self.editor.beginUndoAction() - stxt = txt.strip() - if stxt and stxt[-1] in ("(", "[", "{"): - # indent one more level - self.editor.indent(line) - self.editor.editorCommand(QsciScintilla.SCI_VCHOME) - else: - # indent to the level of the opening brace - openCount = len(re.findall("[({[]", txt)) - closeCount = len(re.findall(r"[)}\]]", txt)) - if openCount > closeCount: - openCount = 0 - closeCount = 0 - openList = list(re.finditer("[({[]", txt)) - index = len(openList) - 1 - while index > -1 and openCount == closeCount: - lastOpenIndex = openList[index].start() - txt2 = txt[lastOpenIndex:] - openCount = len(re.findall("[({[]", txt2)) - closeCount = len(re.findall(r"[)}\]]", txt2)) - index -= 1 - if openCount > closeCount and lastOpenIndex > col: - self.editor.insert( - ' ' * (lastOpenIndex - col + 1)) - self.editor.setCursorPosition( - line, lastOpenIndex + 1) - self.editor.endUndoAction() + elif char == '\n' and self.__indentBrace: + txt = self.editor.text(line - 1) + if re.search(":\r?\n", txt) is None: + self.editor.beginUndoAction() + stxt = txt.strip() + if stxt and stxt[-1] in ("(", "[", "{"): + # indent one more level + self.editor.indent(line) + self.editor.editorCommand(QsciScintilla.SCI_VCHOME) + else: + # indent to the level of the opening brace + openCount = len(re.findall("[({[]", txt)) + closeCount = len(re.findall(r"[)}\]]", txt)) + if openCount > closeCount: + openCount = 0 + closeCount = 0 + openList = list(re.finditer("[({[]", txt)) + index = len(openList) - 1 + while index > -1 and openCount == closeCount: + lastOpenIndex = openList[index].start() + txt2 = txt[lastOpenIndex:] + openCount = len(re.findall("[({[]", txt2)) + closeCount = len(re.findall(r"[)}\]]", txt2)) + index -= 1 + if openCount > closeCount and lastOpenIndex > col: + self.editor.insert( + ' ' * (lastOpenIndex - col + 1)) + self.editor.setCursorPosition( + line, lastOpenIndex + 1) + self.editor.endUndoAction() def __dedentToIf(self): """
--- a/eric6/QScintilla/TypingCompleters/CompleterRuby.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/TypingCompleters/CompleterRuby.py Sun Apr 11 18:45:10 2021 +0200 @@ -88,10 +88,9 @@ # skip matching closing parenthesis elif char in [')', '}', ']']: txt = self.editor.text(line) - if col < len(txt) and char == txt[col]: - if self.__skipBrace: - self.editor.setSelection(line, col, line, col + 1) - self.editor.removeSelectedText() + if col < len(txt) and char == txt[col] and self.__skipBrace: + self.editor.setSelection(line, col, line, col + 1) + self.editor.removeSelectedText() # space # complete inline documentation @@ -102,34 +101,29 @@ # comma # insert blank - elif char == ',': - if self.__insertBlank: - self.editor.insert(' ') - self.editor.setCursorPosition(line, col + 1) + elif char == ',' and self.__insertBlank: + self.editor.insert(' ') + self.editor.setCursorPosition(line, col + 1) # open curly brace # insert closing brace - elif char == '{': - if self.__insertClosingBrace: - self.editor.insert('}') + elif char == '{' and self.__insertClosingBrace: + self.editor.insert('}') # open bracket # insert closing bracket - elif char == '[': - if self.__insertClosingBrace: - self.editor.insert(']') + elif char == '[' and self.__insertClosingBrace: + self.editor.insert(']') # double quote # insert double quote - elif char == '"': - if self.__insertQuote: - self.editor.insert('"') + elif char == '"' and self.__insertQuote: + self.editor.insert('"') # quote # insert quote - elif char == '\'': - if self.__insertQuote: - self.editor.insert('\'') + elif char == '\'' and self.__insertQuote: + self.editor.insert('\'') # new line # indent to opening brace, complete inline documentation
--- a/eric6/QScintilla/TypingCompleters/CompleterYaml.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/QScintilla/TypingCompleters/CompleterYaml.py Sun Apr 11 18:45:10 2021 +0200 @@ -77,31 +77,27 @@ # open curly brace # insert closing brace - if char == '{': - if self.__insertClosingBrace: - self.editor.insert('}') + if char == '{' and self.__insertClosingBrace: + self.editor.insert('}') # open bracket # insert closing bracket - elif char == '[': - if self.__insertClosingBrace: - self.editor.insert(']') + elif char == '[' and self.__insertClosingBrace: + self.editor.insert(']') # closing parenthesis # skip matching closing parenthesis elif char in ['}', ']']: txt = self.editor.text(line) - if col < len(txt) and char == txt[col]: - if self.__skipBrace: - self.editor.setSelection(line, col, line, col + 1) - self.editor.removeSelectedText() + if col < len(txt) and char == txt[col] and self.__skipBrace: + self.editor.setSelection(line, col, line, col + 1) + self.editor.removeSelectedText() # dash # insert blank - elif char == '-': - if self.__insertBlankDash: - self.editor.insert(' ') - self.editor.setCursorPosition(line, col + 1) + elif char == '-' and self.__insertBlankDash: + self.editor.insert(' ') + self.editor.setCursorPosition(line, col + 1) # colon # 1. skip colon if not last character @@ -112,59 +108,53 @@ if self.__colonDetection: self.editor.setSelection(line, col, line, col + 1) self.editor.removeSelectedText() - elif self.__insertBlankColon: - if col == len(text.rstrip()): - self.editor.insert(' ') - self.editor.setCursorPosition(line, col + 1) - - # question mark - # insert blank - elif char == '?': - if self.__insertBlankQuestion: + elif self.__insertBlankColon and col == len(text.rstrip()): self.editor.insert(' ') self.editor.setCursorPosition(line, col + 1) + # question mark + # insert blank + elif char == '?' and self.__insertBlankQuestion: + self.editor.insert(' ') + self.editor.setCursorPosition(line, col + 1) + # comma # insert blank - elif char == ',': - if self.__insertBlankComma: - self.editor.insert(' ') - self.editor.setCursorPosition(line, col + 1) + elif char == ',' and self.__insertBlankComma: + self.editor.insert(' ') + self.editor.setCursorPosition(line, col + 1) # double quote # insert double quote - elif char == '"': - if self.__insertQuote: - self.editor.insert('"') + elif char == '"' and self.__insertQuote: + self.editor.insert('"') # quote # insert quote - elif char == "'": - if self.__insertQuote: - self.editor.insert("'") + elif char == "'" and self.__insertQuote: + self.editor.insert("'") # new line # indent after line ending with ':' - elif char == '\n': - if self.__autoIndentation: - txt = self.editor.text(line - 1) - match = re.search( - "(?:\||\|-|\|\+|>|>-|>\+|-|:)(\s*)\r?\n", - # __IGNORE_WARNING_W605__ - txt) - if match is not None: - startBlanks = match.start(1) - endBlanks = match.end(1) - if startBlanks != -1 and startBlanks != endBlanks: - # previous line ends with whitespace, e.g. caused by - # blank insertion above - self.editor.setSelection(line - 1, startBlanks, - line - 1, endBlanks) - self.editor.removeSelectedText() - - self.editor.indent(line) - self.editor.setCursorPosition(line, 0) - self.editor.editorCommand(QsciScintilla.SCI_VCHOME) + elif char == '\n' and self.__autoIndentation: + txt = self.editor.text(line - 1) + match = re.search( + "(?:\||\|-|\|\+|>|>-|>\+|-|:)(\s*)\r?\n", + # __IGNORE_WARNING_W605__ + txt) + if match is not None: + startBlanks = match.start(1) + endBlanks = match.end(1) + if startBlanks != -1 and startBlanks != endBlanks: + # previous line ends with whitespace, e.g. caused by + # blank insertion above + self.editor.setSelection(line - 1, startBlanks, + line - 1, endBlanks) + self.editor.removeSelectedText() + + self.editor.indent(line) + self.editor.setCursorPosition(line, 0) + self.editor.editorCommand(QsciScintilla.SCI_VCHOME) def __inComment(self, line, col): """
--- a/eric6/eric6_doc.py Sun Apr 11 16:53:48 2021 +0200 +++ b/eric6/eric6_doc.py Sun Apr 11 18:45:10 2021 +0200 @@ -205,9 +205,8 @@ elif k in ["-c", "--style-sheet"]: stylesheetFile = v elif k in ["-t", "--extension"]: - if v.strip(): - if not v.startswith("."): - v = ".{0}".format(v) + if v.strip() and not v.startswith("."): + v = ".{0}".format(v) supportedExtensions.append(v) elif k == "--eol": if v.lower() == "cr":