Wed, 21 Sep 2022 16:42:20 +0200
Reformatted source code with 'Black'.
--- a/PluginDjango.epj Fri Dec 31 13:17:55 2021 +0100 +++ b/PluginDjango.epj Wed Sep 21 16:42:20 2022 +0200 @@ -1,19 +1,21 @@ { "header": { "comment": "eric project file for project PluginDjango", - "copyright": "Copyright (C) 2021 Detlev Offenbach, detlev@die-offenbachs.de" + "copyright": "Copyright (C) 2022 Detlev Offenbach, detlev@die-offenbachs.de" }, "project": { "AUTHOR": "Detlev Offenbach", "CHECKERSPARMS": { "Pep8Checker": { "AnnotationsChecker": { + "AllowStarArgAny": false, "AllowUntypedDefs": false, "AllowUntypedNested": false, "DispatchDecorators": [ "singledispatch", "singledispatchmethod" ], + "ForceFutureAnnotations": false, "MaximumComplexity": 3, "MaximumLength": 7, "MinimumCoverage": 75, @@ -59,20 +61,25 @@ }, "CopyrightAuthor": "", "CopyrightMinFileSize": 0, - "DocstringType": "eric", + "DocstringType": "eric_black", "EnabledCheckerCategories": "C, D, E, M, N, Y, W", "ExcludeFiles": "*/Ui_*.py, */*_rc.py", - "ExcludeMessages": "C101,E265,E266,E305,E402,M201,M301,M302,M303,M304,M305,M306,M307,M308,M311,M312,M313,M314,M315,M321,M701,M702,M811,M834,N802,N803,N807,N808,N821,W293,W504,Y401,Y402", + "ExcludeMessages": "C101,E265,E266,E305,E402,M201,M301,M302,M303,M304,M305,M306,M307,M308,M311,M312,M313,M314,M315,M321,M701,M702,M811,M834,N802,N803,N807,N808,N821,W293,W503,Y401,Y402", "FixCodes": "", "FixIssues": false, "FutureChecker": "", "HangClosing": false, + "ImportsChecker": { + "ApplicationPackageNames": [], + "BanRelativeImports": "", + "BannedModules": [] + }, "IncludeMessages": "", "LineComplexity": 25, "LineComplexityScore": 10, "MaxCodeComplexity": 10, - "MaxDocLineLength": 79, - "MaxLineLength": 79, + "MaxDocLineLength": 88, + "MaxLineLength": 88, "NoFixCodes": "E501", "RepeatMessages": true, "SecurityChecker": { @@ -128,6 +135,7 @@ } }, "EMAIL": "detlev@die-offenbachs.de", + "EMBEDDED_VENV": false, "EOL": 1, "FILETYPES": { "*.epj": "OTHERS", @@ -173,6 +181,7 @@ }, "INTERFACES": [], "LEXERASSOCS": {}, + "LICENSE": "GNU General Public License v3 or later (GPLv3+)", "MAINSCRIPT": "PluginProjectDjango.py", "MAKEPARAMS": { "MakeEnabled": false, @@ -187,6 +196,7 @@ ".hgignore", "ChangeLog", "PKGLIST", + "PluginDjango.epj", "PluginProjectDjango.zip", "ProjectDjango/APIs", "ProjectDjango/Documentation/LICENSE.GPL3", @@ -197,10 +207,26 @@ "ProjectDjango/icons/django-dark.svg", "ProjectDjango/icons/django-light.svg", "ProjectDjango/icons/django64-dark.svg", - "ProjectDjango/icons/django64-light.svg", - "PluginDjango.epj" + "ProjectDjango/icons/django64-light.svg" ], - "OTHERTOOLSPARMS": {}, + "OTHERTOOLSPARMS": { + "Black": { + "exclude": "/(\\.direnv|\\.eggs|\\.git|\\.hg|\\.mypy_cache|\\.nox|\\.tox|\\.venv|venv|\\.svn|_build|buck-out|build|dist|__pypackages__)/", + "extend-exclude": "", + "force-exclude": "", + "line-length": 88, + "skip-magic-trailing-comma": false, + "skip-string-normalization": false, + "source": "project", + "target-version": [ + "py311", + "py310", + "py39", + "py38", + "py37" + ] + } + }, "PACKAGERSPARMS": {}, "PROGLANGUAGE": "Python3", "PROJECTTYPE": "E7Plugin", @@ -236,6 +262,7 @@ "SPELLEXCLUDES": "", "SPELLLANGUAGE": "en", "SPELLWORDS": "", + "TESTING_FRAMEWORK": "", "TRANSLATIONEXCEPTIONS": [], "TRANSLATIONPATTERN": "ProjectDjango/i18n/django_%language%.ts", "TRANSLATIONS": [
--- a/PluginProjectDjango.py Fri Dec 31 13:17:55 2021 +0100 +++ b/PluginProjectDjango.py Wed Sep 21 16:42:20 2022 +0200 @@ -30,9 +30,7 @@ className = "ProjectDjangoPlugin" packageName = "ProjectDjango" shortDescription = "Project support for Django projects." -longDescription = ( - """This plugin implements project support for Django projects.""" -) +longDescription = """This plugin implements project support for Django projects.""" needsRestart = False pyqtApi = 2 # End-of-Header @@ -45,16 +43,15 @@ def apiFiles(language): """ Module function to return the API files made available by this plugin. - + @param language language to get APIs for @type str @return list of API filenames @rtype list of str """ if language in ["Python3"]: - apisDir = os.path.join(os.path.dirname(__file__), - "ProjectDjango", "APIs") - apis = glob.glob(os.path.join(apisDir, '*.api')) + apisDir = os.path.join(os.path.dirname(__file__), "ProjectDjango", "APIs") + apis = glob.glob(os.path.join(apisDir, "*.api")) else: apis = [] return apis @@ -63,7 +60,7 @@ def createDjangoPage(configDlg): """ Module function to create the Django configuration page. - + @param configDlg reference to the configuration dialog @type ConfigurationWidget @return reference to the configuration page @@ -71,26 +68,29 @@ """ global djangoPluginObject from ProjectDjango.ConfigurationPage.DjangoPage import DjangoPage + page = DjangoPage(djangoPluginObject) return page - + def getConfigData(): """ Module function returning data as required by the configuration dialog. - + @return dictionary containing the relevant data @rtype dict """ usesDarkPalette = ericApp().usesDarkPalette() iconSuffix = "dark" if usesDarkPalette else "light" - + return { "djangoPage": [ QCoreApplication.translate("ProjectDjangoPlugin", "Django"), - os.path.join("ProjectDjango", "icons", - "django-{0}".format(iconSuffix)), - createDjangoPage, None, None], + os.path.join("ProjectDjango", "icons", "django-{0}".format(iconSuffix)), + createDjangoPage, + None, + None, + ], } @@ -107,45 +107,38 @@ """ Class implementing the Django project plugin. """ + PreferencesKey = "Django" - + lexerAssociations = { "*.htm": "Pygments|HTML+Django/Jinja", "*.html": "Pygments|HTML+Django/Jinja", } - + def __init__(self, ui): """ Constructor - + @param ui reference to the user interface object @type UserInterface """ QObject.__init__(self, ui) self.__ui = ui self.__initialize() - + self.__defaults = { "VirtualEnvironmentNamePy3": "", - "Python3ConsoleType": "ipython", - "ServerAddress": "", - "RecentNumberApps": 10, "UseIPv6": False, "UseThreading": True, - "TranslationsEditor": "", "FuzzyTranslations": False, - "UseExternalBrowser": False, - "CheckDeployMode": False, - "RecentNumberTestData": 10, "KeepTestDatabase": False, - "RecentNumberDatabaseNames": 10, } if isWindowsPlatform(): @@ -157,120 +150,131 @@ else: self.__defaults["ConsoleCommandNoClose"] = "konsole --noclose -e" self.__defaults["ConsoleCommand"] = "konsole -e" - + self.__translator = None self.__loadTranslator() - + def __initialize(self): """ Private slot to (re)initialize the plugin. """ self.__object = None - + self.__mainMenu = None self.__mainAct = None self.__separatorAct = None - + self.__ericProject = ericApp().getObject("Project") - + self.__supportedVariants = [] - + def activate(self): """ Public method to activate this plugin. - + @return tuple of None and activation status @rtype bool """ global djangoPluginObject djangoPluginObject = self - + usesDarkPalette = ericApp().usesDarkPalette() iconSuffix = "dark" if usesDarkPalette else "light" - + self.__object = Project(self, iconSuffix, self.__ui) self.__object.initActions() ericApp().registerPluginObject("ProjectDjango", self.__object) - + self.__mainMenu = self.__object.initMenu() - + self.__supportedVariants = self.__object.supportedPythonVariants() - + if self.__supportedVariants: self.__ericProject.registerProjectType( - "Django", self.tr("Django"), + "Django", + self.tr("Django"), self.fileTypesCallback, lexerAssociationCallback=self.lexerAssociationCallback, binaryTranslationsCallback=self.binaryTranslationsCallback, - progLanguages=self.__supportedVariants[:]) - + progLanguages=self.__supportedVariants[:], + ) + from Project.ProjectBrowser import ( - SourcesBrowserFlag, FormsBrowserFlag, TranslationsBrowserFlag, - OthersBrowserFlag + SourcesBrowserFlag, + FormsBrowserFlag, + TranslationsBrowserFlag, + OthersBrowserFlag, ) + Preferences.setProjectBrowserFlagsDefault( "Django", - SourcesBrowserFlag | FormsBrowserFlag | - TranslationsBrowserFlag | OthersBrowserFlag, + SourcesBrowserFlag + | FormsBrowserFlag + | TranslationsBrowserFlag + | OthersBrowserFlag, ) - + if self.__ericProject.isOpen(): self.__projectOpened() self.__object.projectOpenedHooks() - - ericApp().getObject("Project").projectOpened.connect( - self.__projectOpened) - ericApp().getObject("Project").projectClosed.connect( - self.__projectClosed) - ericApp().getObject("Project").newProject.connect( - self.__projectOpened) - + + ericApp().getObject("Project").projectOpened.connect(self.__projectOpened) + ericApp().getObject("Project").projectClosed.connect(self.__projectClosed) + ericApp().getObject("Project").newProject.connect(self.__projectOpened) + ericApp().getObject("Project").projectOpenedHooks.connect( - self.__object.projectOpenedHooks) + self.__object.projectOpenedHooks + ) ericApp().getObject("Project").projectClosedHooks.connect( - self.__object.projectClosedHooks) + self.__object.projectClosedHooks + ) ericApp().getObject("Project").newProjectHooks.connect( - self.__object.projectOpenedHooks) - + self.__object.projectOpenedHooks + ) + ericApp().getObject("Project").projectAboutToBeCreated.connect( - self.__object.startProjectOrApplication) + self.__object.startProjectOrApplication + ) ericApp().getObject("Project").newProject.connect( - self.__object.newProjectCreated) - + self.__object.newProjectCreated + ) + return None, True - + def deactivate(self): """ Public method to deactivate this plugin. """ ericApp().unregisterPluginObject("ProjectDjango") - - ericApp().getObject("Project").projectOpened.disconnect( - self.__projectOpened) - ericApp().getObject("Project").projectClosed.disconnect( - self.__projectClosed) - ericApp().getObject("Project").newProject.disconnect( - self.__projectOpened) - + + ericApp().getObject("Project").projectOpened.disconnect(self.__projectOpened) + ericApp().getObject("Project").projectClosed.disconnect(self.__projectClosed) + ericApp().getObject("Project").newProject.disconnect(self.__projectOpened) + ericApp().getObject("Project").projectOpenedHooks.disconnect( - self.__object.projectOpenedHooks) + self.__object.projectOpenedHooks + ) ericApp().getObject("Project").projectClosedHooks.disconnect( - self.__object.projectClosedHooks) + self.__object.projectClosedHooks + ) ericApp().getObject("Project").newProjectHooks.disconnect( - self.__object.projectOpenedHooks) - + self.__object.projectOpenedHooks + ) + ericApp().getObject("Project").projectAboutToBeCreated.disconnect( - self.__object.startProjectOrApplication) + self.__object.startProjectOrApplication + ) ericApp().getObject("Project").newProject.disconnect( - self.__object.newProjectCreated) - + self.__object.newProjectCreated + ) + self.__ericProject.unregisterProjectType("Django") - + self.__object.projectClosedHooks() self.__projectClosed() - + self.__initialize() - + def __loadTranslator(self): """ Private method to load the translation file. @@ -279,7 +283,8 @@ loc = self.__ui.getLocale() if loc and loc != "C": locale_dir = os.path.join( - os.path.dirname(__file__), "ProjectDjango", "i18n") + os.path.dirname(__file__), "ProjectDjango", "i18n" + ) translation = "django_{0}".format(loc) translator = QTranslator(None) loaded = translator.load(translation, locale_dir) @@ -287,10 +292,12 @@ self.__translator = translator ericApp().installTranslator(self.__translator) else: - print("Warning: translation file '{0}' could not be" - " loaded.".format(translation)) + print( + "Warning: translation file '{0}' could not be" + " loaded.".format(translation) + ) print("Using default.") - + def __projectOpened(self): """ Private slot to handle the projectOpened signal. @@ -299,10 +306,10 @@ projectToolsMenu = self.__ui.getMenu("project_tools") insertBeforeAct = projectToolsMenu.actions()[0] self.__mainAct = projectToolsMenu.insertMenu( - insertBeforeAct, self.__mainMenu) - self.__separatorAct = projectToolsMenu.insertSeparator( - insertBeforeAct) - + insertBeforeAct, self.__mainMenu + ) + self.__separatorAct = projectToolsMenu.insertSeparator(insertBeforeAct) + def __projectClosed(self): """ Private slot to handle the projectClosed signal. @@ -314,11 +321,11 @@ self.__mainAct = None self.__separatorAct = None self.__object.projectClosed() - + def fileTypesCallback(self): """ Public method get the filetype associations of the Django project type. - + @return dictionary with file type associations @rtype dict """ @@ -332,16 +339,16 @@ "*.mo": "TRANSLATIONS", "*.py": "SOURCES", } - if self.__ericProject.getProjectType() == "Django" else - {} + if self.__ericProject.getProjectType() == "Django" + else {} ) return fileTypes - + def lexerAssociationCallback(self, filename): """ Public method to get the lexer association of the Django project type for a file. - + @param filename name of the file @type str @return name of the lexer (Pygments lexers are prefixed with @@ -351,14 +358,14 @@ for pattern, language in self.lexerAssociations.items(): if fnmatch.fnmatch(filename, pattern): return language - + return "" - + def binaryTranslationsCallback(self, filename): """ Public method to determine the filename of a compiled translation file given the translation source file. - + @param filename name of the translation source file @type str @return name of the binary translation file @@ -367,45 +374,56 @@ if filename.endswith(".po"): filename = filename.replace(".po", ".mo") return filename - + def getPreferences(self, key): """ Public method to retrieve the various settings. - + @param key the key of the value to get @type str @return value of the requested setting @rtype Any """ if key in ["RecentNumberApps", "RecentNumberTestData"]: - return int(Preferences.Prefs.settings.value( - self.PreferencesKey + "/" + key, self.__defaults[key])) - elif key in ["UseIPv6", "UseThreading", - "UseExternalBrowser", "CheckDeployMode", - "KeepTestDatabase", "FuzzyTranslations", ]: - return Preferences.toBool(Preferences.Prefs.settings.value( - self.PreferencesKey + "/" + key, self.__defaults[key])) + return int( + Preferences.Prefs.settings.value( + self.PreferencesKey + "/" + key, self.__defaults[key] + ) + ) + elif key in [ + "UseIPv6", + "UseThreading", + "UseExternalBrowser", + "CheckDeployMode", + "KeepTestDatabase", + "FuzzyTranslations", + ]: + return Preferences.toBool( + Preferences.Prefs.settings.value( + self.PreferencesKey + "/" + key, self.__defaults[key] + ) + ) else: return Preferences.Prefs.settings.value( - self.PreferencesKey + "/" + key, self.__defaults[key]) - + self.PreferencesKey + "/" + key, self.__defaults[key] + ) + def setPreferences(self, key, value): """ Public method to store the various settings. - + @param key the key of the setting to be set @type str @param value value to be set @type Any """ - Preferences.Prefs.settings.setValue( - self.PreferencesKey + "/" + key, value) - + Preferences.Prefs.settings.setValue(self.PreferencesKey + "/" + key, value) + if key in ["VirtualEnvironmentNamePy3"]: self.__reregisterProjectType() elif key == "TranslationsEditor" and self.__object: self.__object.registerOpenHook() - + def __reregisterProjectType(self): """ Private method to re-register the project type. @@ -414,21 +432,23 @@ if supportedVariants != self.__supportedVariants: # step 1: unregister self.__ericProject.unregisterProjectType("Django") - + # step 2: register again with new language settings self.__supportedVariants = supportedVariants if self.__supportedVariants: self.__ericProject.registerProjectType( - "Django", self.tr("Django"), + "Django", + self.tr("Django"), self.fileTypesCallback, lexerAssociationCallback=self.lexerAssociationCallback, binaryTranslationsCallback=self.binaryTranslationsCallback, - progLanguages=self.__supportedVariants[:]) - + progLanguages=self.__supportedVariants[:], + ) + def getMenu(self, name): """ Public method to get a reference to the requested menu. - + @param name name of the menu (string) @return reference to the menu (QMenu) or None, if no menu with the given name exists @@ -437,11 +457,11 @@ return self.__object.getMenu(name) else: return None - + def getMenuNames(self): """ Public method to get the names of all menus. - + @return menu names (list of string) """ if self.__object is not None: @@ -449,5 +469,6 @@ else: return [] + # # eflag: noqa = M801
--- a/ProjectDjango/ConfigurationPage/DjangoPage.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/ConfigurationPage/DjangoPage.py Wed Sep 21 16:42:20 2022 +0200 @@ -10,9 +10,7 @@ from EricWidgets.EricApplication import ericApp from EricWidgets.EricPathPicker import EricPathPickerModes -from Preferences.ConfigurationPages.ConfigurationPageBase import ( - ConfigurationPageBase -) +from Preferences.ConfigurationPages.ConfigurationPageBase import ConfigurationPageBase from .Ui_DjangoPage import Ui_DjangoPage from Globals import isWindowsPlatform, isMacPlatform @@ -22,21 +20,22 @@ """ Class implementing the Django configuration page. """ + def __init__(self, plugin): """ Constructor - + @param plugin reference to the plugin object """ super().__init__() self.setupUi(self) self.setObjectName("DjangoPage") - + self.translationsPicker.setMode(EricPathPickerModes.OPEN_FILE_MODE) self.translationsPicker.setFilters(self.tr("All Files (*)")) - + self.__plugin = plugin - + consoleList = [] if isWindowsPlatform(): consoleList.append("cmd.exe /c") @@ -50,7 +49,7 @@ consoleList.append("mate-terminal -e") consoleList.append("xfce4-terminal -e") consoleList.append("xterm -e") - + consoleNoCloseList = [] if isWindowsPlatform(): consoleNoCloseList.append("cmd.exe /k") @@ -64,86 +63,92 @@ consoleNoCloseList.append("mate-terminal --profile=<noclose> -e") consoleNoCloseList.append("xfce4-terminal --hold -e") consoleNoCloseList.append("xterm -hold -e") - + self.consoleCommandCombo.addItems(consoleList) self.consoleCommandNoCloseCombo.addItems(consoleNoCloseList) - + self.py3ShellCombo.addItem(self.tr("Plain Python"), "python") self.py3ShellCombo.addItem(self.tr("IPython"), "ipython") self.py3ShellCombo.addItem(self.tr("bpython"), "bpython") - + venvManager = ericApp().getObject("VirtualEnvManager") - + self.py3VenvNameComboBox.addItems( - [""] + sorted(venvManager.getVirtualenvNames())) - + [""] + sorted(venvManager.getVirtualenvNames()) + ) + # set initial values self.consoleCommandCombo.setEditText( - self.__plugin.getPreferences("ConsoleCommand")) + self.__plugin.getPreferences("ConsoleCommand") + ) self.consoleCommandNoCloseCombo.setEditText( - self.__plugin.getPreferences("ConsoleCommandNoClose")) - - self.serverAddressEdit.setText( - self.__plugin.getPreferences("ServerAddress")) - self.ipv6CheckBox.setChecked( - self.__plugin.getPreferences("UseIPv6")) - self.threadingCheckBox.setChecked( - self.__plugin.getPreferences("UseThreading")) - + self.__plugin.getPreferences("ConsoleCommandNoClose") + ) + + self.serverAddressEdit.setText(self.__plugin.getPreferences("ServerAddress")) + self.ipv6CheckBox.setChecked(self.__plugin.getPreferences("UseIPv6")) + self.threadingCheckBox.setChecked(self.__plugin.getPreferences("UseThreading")) + self.externalBrowserCheckBox.setChecked( - self.__plugin.getPreferences("UseExternalBrowser")) - + self.__plugin.getPreferences("UseExternalBrowser") + ) + self.appsRecentSpinBox.setValue( - self.__plugin.getPreferences("RecentNumberApps")) - - venvName = self.__plugin.getPreferences( - "VirtualEnvironmentNamePy3") + self.__plugin.getPreferences("RecentNumberApps") + ) + + venvName = self.__plugin.getPreferences("VirtualEnvironmentNamePy3") if venvName: index = self.py3VenvNameComboBox.findText(venvName) if index < 0: index = 0 self.py3VenvNameComboBox.setCurrentIndex(index) - - self.py3ShellCombo.setCurrentIndex(self.py3ShellCombo.findData( - self.__plugin.getPreferences("Python3ConsoleType"))) - + + self.py3ShellCombo.setCurrentIndex( + self.py3ShellCombo.findData( + self.__plugin.getPreferences("Python3ConsoleType") + ) + ) + self.translationsPicker.setText( - self.__plugin.getPreferences("TranslationsEditor")) + self.__plugin.getPreferences("TranslationsEditor") + ) self.fuzzyTranslationsCheckBox.setChecked( - self.__plugin.getPreferences("FuzzyTranslations")) - + self.__plugin.getPreferences("FuzzyTranslations") + ) + def save(self): """ Public slot to save the Django configuration. """ self.__plugin.setPreferences( - "ConsoleCommand", - self.consoleCommandCombo.currentText()) - self.__plugin.setPreferences( - "ConsoleCommandNoClose", - self.consoleCommandNoCloseCombo.currentText()) - - self.__plugin.setPreferences( - "ServerAddress", self.serverAddressEdit.text()) - self.__plugin.setPreferences( - "UseIPv6", self.ipv6CheckBox.isChecked()) + "ConsoleCommand", self.consoleCommandCombo.currentText() + ) self.__plugin.setPreferences( - "UseThreading", self.threadingCheckBox.isChecked()) - - self.__plugin.setPreferences( - "UseExternalBrowser", self.externalBrowserCheckBox.isChecked()) - + "ConsoleCommandNoClose", self.consoleCommandNoCloseCombo.currentText() + ) + + self.__plugin.setPreferences("ServerAddress", self.serverAddressEdit.text()) + self.__plugin.setPreferences("UseIPv6", self.ipv6CheckBox.isChecked()) + self.__plugin.setPreferences("UseThreading", self.threadingCheckBox.isChecked()) + self.__plugin.setPreferences( - "RecentNumberApps", self.appsRecentSpinBox.value()) - + "UseExternalBrowser", self.externalBrowserCheckBox.isChecked() + ) + + self.__plugin.setPreferences("RecentNumberApps", self.appsRecentSpinBox.value()) + self.__plugin.setPreferences( - "VirtualEnvironmentNamePy3", - self.py3VenvNameComboBox.currentText()) + "VirtualEnvironmentNamePy3", self.py3VenvNameComboBox.currentText() + ) self.__plugin.setPreferences( "Python3ConsoleType", - self.py3ShellCombo.itemData(self.py3ShellCombo.currentIndex())) - + self.py3ShellCombo.itemData(self.py3ShellCombo.currentIndex()), + ) + self.__plugin.setPreferences( - "TranslationsEditor", self.translationsPicker.text()) + "TranslationsEditor", self.translationsPicker.text() + ) self.__plugin.setPreferences( - "FuzzyTranslations", self.fuzzyTranslationsCheckBox.isChecked()) + "FuzzyTranslations", self.fuzzyTranslationsCheckBox.isChecked() + )
--- a/ProjectDjango/DjangoCheckOptionsDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoCheckOptionsDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -25,10 +25,11 @@ """ Class implementing a dialog to enter the options for a check operation. """ + def __init__(self, python, path, apps, deployMode, parent=None): """ Constructor - + @param python path of the Python executable @type str @param path site path to run the manage.py script with @@ -42,28 +43,28 @@ """ super().__init__(parent) self.setupUi(self) - + self.settingsFileButton.setIcon(UI.PixmapCache.getIcon("open")) - + self.__python = python self.__path = path - + self.appsComboBox.addItems([""] + apps) - + self.deployCheckBox.setChecked(deployMode) self.on_deployCheckBox_toggled(deployMode) - + @pyqtSlot(bool) def on_deployCheckBox_toggled(self, checked): """ Private slot handling a change of the deploy check box. - + @param checked state of the check box @type bool """ self.settingsFileGroup.setEnabled(checked) self.__populateTagsList(checked) - + @pyqtSlot() def on_settingsFileButton_clicked(self): """ @@ -73,37 +74,31 @@ if not path: path = self.__path settingsFile = EricFileDialog.getOpenFileName( - self, - self.tr("Select settings file"), - path, - self.tr("Python Files (*.py)")) - + self, self.tr("Select settings file"), path, self.tr("Python Files (*.py)") + ) + if settingsFile: self.settingsFileEdit.setText(self.__pathToModule(settingsFile)) - + def __pathToModule(self, path): """ Private method to convert a file path including a .py extension to a module name. - + @param path file path to be converted @type str @return module name @rtype str """ - start = ( - self.__path[:-1] - if self.__path.endswith(("/", "\\")) else - self.__path - ) + start = self.__path[:-1] if self.__path.endswith(("/", "\\")) else self.__path relPath = Utilities.relativeUniversalPath(path, start) mod = os.path.splitext(relPath)[0].replace("/", ".") return mod - + def __moduleToPath(self, moduleName): """ Private method to convert a module name to an file path. - + @param moduleName module name to be converted @type str @return file path @@ -113,16 +108,16 @@ mod = "{0}.py".format(moduleName.replace(".", "/")) if not os.path.isabs(mod): mod = os.path.join(self.__path, mod) - + path = Utilities.toNativeSeparators(mod) else: path = "" return path - + def __populateTagsList(self, deployMode): """ Private slot to populate the tags list. - + @param deployMode flag indicating the deployment mode @type bool """ @@ -130,10 +125,10 @@ selectedTags = [] for itm in self.tagsList.selectedItems(): selectedTags.append(itm.text()) - + # step 2: clear the list self.tagsList.clear() - + # step 3: get the available tags and populate the list args = [] args.append("manage.py") @@ -141,28 +136,30 @@ args.append("--list-tags") if deployMode: args.append("--deploy") - + proc = QProcess() if self.__path: proc.setWorkingDirectory(self.__path) proc.start(self.__python, args) if proc.waitForStarted() and proc.waitForFinished(): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), 'replace') + output = str( + proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + "replace", + ) for line in output.splitlines(): self.tagsList.addItem(line.strip()) - + # step 4: re-select tags for tag in selectedTags: - items = self.tagsList.findItems( - tag, Qt.MatchFlag.MatchCaseSensitive) + items = self.tagsList.findItems(tag, Qt.MatchFlag.MatchCaseSensitive) if items: items[0].setSelected(True) - + def getData(self): """ Public method to get the options for the check operation. - + @return tuple containing the deployment flag, list of selected tags, applications string and the settings file @rtype tuple of bool, list of str, str and str @@ -170,7 +167,7 @@ selectedTags = [] for itm in self.tagsList.selectedItems(): selectedTags.append(itm.text()) - + return ( self.deployCheckBox.isChecked(), selectedTags,
--- a/ProjectDjango/DjangoDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -11,7 +11,11 @@ from PyQt6.QtCore import pyqtSlot, QProcess, QTimer, QFileInfo from PyQt6.QtWidgets import ( - QDialog, QDialogButtonBox, QAbstractButton, QTextEdit, QLineEdit + QDialog, + QDialogButtonBox, + QAbstractButton, + QTextEdit, + QLineEdit, ) from EricWidgets import EricMessageBox, EricFileDialog @@ -26,18 +30,26 @@ class DjangoDialog(QDialog, Ui_DjangoDialog): """ Class implementing a dialog starting a process and showing its output. - + It starts a QProcess and displays a dialog that shows the output of the process. The dialog is modal, which causes a synchronized execution of the process. """ - def __init__(self, text, fixed=False, linewrap=True, - msgSuccess=None, msgError=None, - saveFilters=None, showInput=False, - parent=None): + + def __init__( + self, + text, + fixed=False, + linewrap=True, + msgSuccess=None, + msgError=None, + saveFilters=None, + showInput=False, + parent=None, + ): """ Constructor - + @param text text to be shown by the label @type str @param fixed flag indicating a fixed font should be used @@ -57,19 +69,15 @@ """ super().__init__(parent) self.setupUi(self) - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setDefault(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Save).setEnabled(False) + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Save).setEnabled(False) if saveFilters is None: - self.buttonBox.button( - QDialogButtonBox.StandardButton.Save).setHidden(True) - + self.buttonBox.button(QDialogButtonBox.StandardButton.Save).setHidden(True) + self.ioEncoding = Preferences.getSystem("IOEncoding") - + self.proc = None self.argsLists = [] self.workingDir = None @@ -79,99 +87,84 @@ self.fileFilters = saveFilters self.showInput = showInput self.intercept = False - + self.outputGroup.setTitle(text) - + if fixed: if isWindowsPlatform(): self.resultbox.setFontFamily("Lucida Console") else: self.resultbox.setFontFamily("Monospace") - + if not linewrap: self.resultbox.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) - + @pyqtSlot(QAbstractButton) def on_buttonBox_clicked(self, button): """ Private slot called by a button of the button box clicked. - + @param button button that was clicked @type QAbstractButton """ - if button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Close - ): + if button == self.buttonBox.button(QDialogButtonBox.StandardButton.Close): self.close() - elif button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel - ): + elif button == self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel): self.__finish() - elif button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Save - ): + elif button == self.buttonBox.button(QDialogButtonBox.StandardButton.Save): self.__saveData() - + def __finish(self): """ Private slot called when the process finished or the user pressed the button. """ if ( - self.proc is not None and - self.proc.state() != QProcess.ProcessState.NotRunning + self.proc is not None + and self.proc.state() != QProcess.ProcessState.NotRunning ): self.proc.terminate() QTimer.singleShot(2000, self.proc.kill) self.proc.waitForFinished(3000) - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setDefault(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Save).setEnabled(True) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setDefault(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Save).setEnabled(True) + self.inputGroup.setEnabled(False) self.inputGroup.hide() - + self.proc = None - + if self.argsLists: args = self.argsLists[0][:] del self.argsLists[0] - self.startProcess(args, self.workingDir, - mergedOutput=self.mergedOutput) - + self.startProcess(args, self.workingDir, mergedOutput=self.mergedOutput) + def __procFinished(self, exitCode, exitStatus): """ Private slot connected to the finished signal. - + @param exitCode exit code of the process @type int @param exitStatus exit status of the process @type QProcess.ExitStatus """ - self.normal = ( - exitStatus == QProcess.ExitStatus.NormalExit and - exitCode == 0 - ) + self.normal = exitStatus == QProcess.ExitStatus.NormalExit and exitCode == 0 self.__finish() - + if self.normal and self.msgSuccess: self.resultbox.insertPlainText(self.msgSuccess) elif not self.normal and self.msgError: self.resultbox.insertPlainText(self.msgError) self.errorGroup.show() self.resultbox.ensureCursorVisible() - - def startProcess(self, args, workingDir=None, showCommand=True, - mergedOutput=False): + + def startProcess(self, args, workingDir=None, showCommand=True, mergedOutput=False): """ Public slot used to start the process. - + @param args list of arguments for the process @type list of str @param workingDir working directory for the process @@ -184,28 +177,27 @@ @rtype bool """ self.errorGroup.hide() - + self.normal = False - + self.proc = QProcess() if mergedOutput: - self.proc.setProcessChannelMode( - QProcess.ProcessChannelMode.MergedChannels) - + self.proc.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels) + if showCommand: - self.resultbox.append(' '.join(args)) - self.resultbox.append('') - + self.resultbox.append(" ".join(args)) + self.resultbox.append("") + self.proc.finished.connect(self.__procFinished) self.proc.readyReadStandardOutput.connect(self.__readStdout) self.proc.readyReadStandardError.connect(self.__readStderr) - + if workingDir: self.proc.setWorkingDirectory(workingDir) self.workingDir = workingDir else: self.workingDir = "" - + prog = args[0] del args[0] self.proc.start(prog, args) @@ -215,11 +207,12 @@ self.inputGroup.setEnabled(False) EricMessageBox.critical( self, - self.tr('Process Generation Error'), + self.tr("Process Generation Error"), self.tr( - 'The process {0} could not be started. ' - 'Ensure, that it is in the search path.' - ).format(prog)) + "The process {0} could not be started. " + "Ensure, that it is in the search path." + ).format(prog), + ) else: if self.showInput: self.inputGroup.setEnabled(True) @@ -227,14 +220,13 @@ else: self.inputGroup.setEnabled(False) self.inputGroup.hide() - + return procStarted - - def startBatchProcesses(self, argsLists, workingDir=None, - mergedOutput=False): + + def startBatchProcesses(self, argsLists, workingDir=None, mergedOutput=False): """ Public slot used to start a batch of processes. - + @param argsLists list of lists of arguments for the processes @type list of list of str @param workingDir working directory for the process @@ -247,83 +239,77 @@ self.argsLists = argsLists[:] self.workingDir = workingDir self.mergedOutput = mergedOutput - + # start the first process args = self.argsLists[0][:] del self.argsLists[0] - res = self.startProcess(args, self.workingDir, - mergedOutput=self.mergedOutput) + res = self.startProcess(args, self.workingDir, mergedOutput=self.mergedOutput) if not res: self.argsLists = [] - + return res - + def normalExit(self): """ Public method to check for a normal process termination. - + @return flag indicating normal process termination @rtype bool """ return self.normal - + def normalExitWithoutErrors(self): """ Public method to check for a normal process termination without error messages. - + @return flag indicating normal process termination @rtype bool """ return self.normal and self.errors.toPlainText() == "" - + def __readStdout(self): """ Private slot to handle the readyReadStdout signal. - + It reads the output of the process, formats it and inserts it into the contents pane. """ if self.proc is not None: - s = str(self.proc.readAllStandardOutput(), self.ioEncoding, - 'replace') + s = str(self.proc.readAllStandardOutput(), self.ioEncoding, "replace") self.resultbox.insertPlainText(s) self.resultbox.ensureCursorVisible() - + def __readStderr(self): """ Private slot to handle the readyReadStderr signal. - + It reads the error output of the process and inserts it into the error pane. """ if self.proc is not None: self.errorGroup.show() - s = str(self.proc.readAllStandardError(), self.ioEncoding, - 'replace') + s = str(self.proc.readAllStandardError(), self.ioEncoding, "replace") self.errors.insertPlainText(s) self.errors.ensureCursorVisible() - + def __saveData(self): """ Private slot to save the output to a file. """ fname, selectedFilter = EricFileDialog.getSaveFileNameAndFilter( - self, - self.tr("Select data file"), - self.workingDir, - self.fileFilters, - None) - + self, self.tr("Select data file"), self.workingDir, self.fileFilters, None + ) + if fname: ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex - + txt = self.resultbox.toPlainText() - + try: with open(fname, "w", encoding="utf-8") as f: f.write(txt) @@ -331,14 +317,16 @@ EricMessageBox.critical( self, self.tr("Error saving data"), - self.tr("""<p>The data could not be written""" - """ to <b>{0}</b></p><p>Reason: {1}</p>""") - .format(fname, str(err))) - + self.tr( + """<p>The data could not be written""" + """ to <b>{0}</b></p><p>Reason: {1}</p>""" + ).format(fname, str(err)), + ) + def on_passwordCheckBox_toggled(self, isOn): """ Private slot to handle the password checkbox toggled. - + @param isOn flag indicating the status of the check box @type bool """ @@ -346,7 +334,7 @@ self.input.setEchoMode(QLineEdit.EchoMode.Password) else: self.input.setEchoMode(QLineEdit.EchoMode.Normal) - + @pyqtSlot() def on_sendButton_clicked(self): """ @@ -354,30 +342,30 @@ """ inputTxt = self.input.text() inputTxt += os.linesep - + if self.passwordCheckBox.isChecked(): self.errors.insertPlainText(os.linesep) self.errors.ensureCursorVisible() else: self.errors.insertPlainText(inputTxt) self.errors.ensureCursorVisible() - + self.proc.write(strToQByteArray(inputTxt)) - + self.input.clear() self.passwordCheckBox.setChecked(False) - + def on_input_returnPressed(self): """ Private slot to handle the press of the return key in the input field. """ self.intercept = True self.on_sendButton_clicked() - + def keyPressEvent(self, evt): """ Protected slot to handle a key press event. - + @param evt the key press event @type QKeyEvent """ @@ -385,5 +373,5 @@ self.intercept = False evt.accept() return - + super().keyPressEvent(evt)
--- a/ProjectDjango/DjangoDiffsettingsDataDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoDiffsettingsDataDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -17,10 +17,11 @@ Class implementing a dialog to enter the data for the 'diffsettings' command. """ + def __init__(self, django, parent=None): """ Constructor - + @param django reference to the Django project object @type Project @param parent reference to the parent widget @@ -28,24 +29,22 @@ """ super().__init__(parent) self.setupUi(self) - + self.formatComboBox.addItem(self.tr("Hash Format"), "hash") self.formatComboBox.addItem(self.tr("Unified Diff"), "unified") - + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + def getData(self): """ Public method to get the dialog data. - + @return tuple containing a flag indicating to show all settings, the name of a module containing the default settings and the output format @rtype tuple of (bool, str, str) """ - outputFormat = self.formatComboBox.itemData( - self.formatComboBox.currentIndex()) - - return (self.allCheckBox.isChecked(), self.defaultEdit.text(), - outputFormat) + outputFormat = self.formatComboBox.itemData(self.formatComboBox.currentIndex()) + + return (self.allCheckBox.isChecked(), self.defaultEdit.text(), outputFormat)
--- a/ProjectDjango/DjangoDumpdataDataDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoDumpdataDataDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -18,10 +18,11 @@ """ Class implementing a dialog to enter the data for the 'dumpdata' command. """ + def __init__(self, project, parent=None): """ Constructor - + @param project reference to the Django project object @type Project @param parent reference to the parent widget @@ -29,27 +30,28 @@ """ super().__init__(parent) self.setupUi(self) - + self.__project = project - + apps = self.__project.getRecentApplications() self.applicationsCombo.addItems(apps) self.excludeCombo.addItems(apps) self.excludeCombo.setEditText("") - + self.formatCombo.addItem(self.tr("JSON"), "json") self.formatCombo.addItem(self.tr("XML"), "xml") with contextlib.suppress(ImportError): - import yaml # __IGNORE_WARNING__ + import yaml # __IGNORE_WARNING__ + self.formatCombo.addItem(self.tr("YAML"), "yaml") - + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + def getData(self): """ Public method to get the data entered into the dialog. - + @return tuple giving the list of applications to work on, the list of applications to exclude, the dump format and the indentation level @rtype tuple of (list of str, list of str, str, int) @@ -60,10 +62,10 @@ appls = applStr.split() else: appls = [] - + exclStr = self.excludeCombo.currentText() excl = exclStr.split() if exclStr else [] - + dumpFormat = self.formatCombo.itemData(self.formatCombo.currentIndex()) - + return appls, excl, dumpFormat, self.indentationSpinBox.value()
--- a/ProjectDjango/DjangoLoaddataDataDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoLoaddataDataDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -24,10 +24,11 @@ """ Class implementing a dialog to enter the data for the 'loaddata' command. """ + def __init__(self, project, parent=None): """ Constructor - + @param project reference to the Django project object @type Project @param parent reference to the parent widget @@ -35,27 +36,25 @@ """ super().__init__(parent) self.setupUi(self) - + self.fixtureFileButton.setIcon(UI.PixmapCache.getIcon("open")) - + self.__project = project - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Ok).setEnabled(False) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + @pyqtSlot(str) def on_fixturesEdit_textChanged(self, txt): """ Private slot to handle a change of the fixtures text. - + @param txt text of the line edit (string) """ - self.buttonBox.button( - QDialogButtonBox.StandardButton.Ok).setEnabled(bool(txt)) - + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(bool(txt)) + @pyqtSlot() def on_fixtureFileButton_clicked(self): """ @@ -63,24 +62,27 @@ """ fileFilters = self.tr("JSON Files (*.json);;XML Files (*.xml);;") with contextlib.suppress(ImportError): - import yaml # __IGNORE_WARNING__ + import yaml # __IGNORE_WARNING__ + fileFilters += self.tr("YAML Files (*.yaml);;") fileFilters += self.tr("All Files (*)") - + fixtureFiles = EricFileDialog.getOpenFileNames( self, self.tr("Select fixture file"), self.__project.getProjectPath(), - fileFilters) - + fileFilters, + ) + if fixtureFiles: - self.fixturesEdit.setText(" ".join( - [Utilities.toNativeSeparators(f) for f in fixtureFiles])) - + self.fixturesEdit.setText( + " ".join([Utilities.toNativeSeparators(f) for f in fixtureFiles]) + ) + def getData(self): """ Public method to get the data entered into the dialog. - + @return tuple containing the list of fixtures, list of apps to exclude, application to search in and a flag indicating to ignore non-existing fields and models @@ -88,9 +90,13 @@ """ fixturesStr = self.fixturesEdit.text() fixtures = fixturesStr.split() - + excludeStr = self.excludeEdit.text() excludes = excludeStr.split() - - return (fixtures, excludes, self.appEdit.text(), - self.ignoreCheckBox.isChecked()) + + return ( + fixtures, + excludes, + self.appEdit.text(), + self.ignoreCheckBox.isChecked(), + )
--- a/ProjectDjango/DjangoMakeMigrationsDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoMakeMigrationsDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -16,10 +16,11 @@ """ Class implementing a dialog to enter the data needed to make migrations. """ + def __init__(self, recentApps, parent=None): """ Constructor - + @param recentApps list of recently entered applications @type list of str @param parent reference to the parent widget @@ -27,13 +28,13 @@ """ super().__init__(parent) self.setupUi(self) - + self.applicationsComboBox.addItems(recentApps) - + def getData(self): """ Public method to get the data for the migration. - + @return tuple containing the application names, a migration name, the dry-run flag, a flag for an empty migration and a flag indicating to fix migration conflicts
--- a/ProjectDjango/DjangoMigrationSelectionDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoMigrationSelectionDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -13,21 +13,18 @@ from PyQt6.QtGui import QIcon from PyQt6.QtWidgets import QDialog -from .Ui_DjangoMigrationSelectionDialog import ( - Ui_DjangoMigrationSelectionDialog -) +from .Ui_DjangoMigrationSelectionDialog import Ui_DjangoMigrationSelectionDialog -class DjangoMigrationSelectionDialog(QDialog, - Ui_DjangoMigrationSelectionDialog): +class DjangoMigrationSelectionDialog(QDialog, Ui_DjangoMigrationSelectionDialog): """ Class implementing a dialog to select an application and migration. """ - def __init__(self, migrations, migrationRequired=False, suffix="", - parent=None): + + def __init__(self, migrations, migrationRequired=False, suffix="", parent=None): """ Constructor - + @param migrations dictionary containing the available migrations @type dict @param migrationRequired flag indicating that a migration must be @@ -40,26 +37,27 @@ """ super().__init__(parent) self.setupUi(self) - - self.__appliedIcon = QIcon(os.path.join( - os.path.dirname(__file__), "icons", "applied-{0}".format(suffix) - )) - + + self.__appliedIcon = QIcon( + os.path.join( + os.path.dirname(__file__), "icons", "applied-{0}".format(suffix) + ) + ) + self.__migrationRequired = migrationRequired - + self.__migrations = migrations self.applicationComboBox.addItems(sorted(self.__migrations.keys())) - self.on_applicationComboBox_activated( - self.applicationComboBox.currentText()) - + self.on_applicationComboBox_activated(self.applicationComboBox.currentText()) + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + @pyqtSlot(str) def on_applicationComboBox_activated(self, app): """ Private slot to update the migrations combo box. - + @param app name of the selected application @type str """ @@ -71,13 +69,15 @@ self.migrationsComboBox.addItem(self.__appliedIcon, migration) else: self.migrationsComboBox.addItem(migration) - + def getData(self): """ Public method to get the selected data. - + @return tuple containing the selected application name and migration @rtype tuple of two str """ - return (self.applicationComboBox.currentText(), - self.migrationsComboBox.currentText()) + return ( + self.applicationComboBox.currentText(), + self.migrationsComboBox.currentText(), + )
--- a/ProjectDjango/DjangoMigrationsListDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoMigrationsListDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -9,9 +9,15 @@ from PyQt6.QtCore import pyqtSlot, Qt, QProcess, QTimer, QPoint from PyQt6.QtWidgets import ( - QDialog, QDialogButtonBox, QAbstractButton, - QHeaderView, QTreeWidgetItem, QMenu, QAbstractItemView, QInputDialog, - QLineEdit + QDialog, + QDialogButtonBox, + QAbstractButton, + QHeaderView, + QTreeWidgetItem, + QMenu, + QAbstractItemView, + QInputDialog, + QLineEdit, ) from EricWidgets import EricMessageBox @@ -25,13 +31,14 @@ """ Class implementing a dialog show a list of all available migrations. """ + MigrationsListMode = "L" MigrationsPlanMode = "P" - + def __init__(self, mode, django, parent=None): """ Constructor - + @param mode mode of the dialog @type str @param django reference to the Django project object @@ -41,114 +48,112 @@ """ super().__init__(parent) self.setupUi(self) - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setDefault(True) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(True) + self.ioEncoding = Preferences.getSystem("IOEncoding") - + self.proc = QProcess() self.proc.finished.connect(self.__procFinished) self.proc.readyReadStandardOutput.connect(self.__readStdout) self.proc.readyReadStandardError.connect(self.__readStderr) - + self.__pyExe = "" self.__sitePath = "" - + self.__django = django - + self.__mode = mode if self.__mode == DjangoMigrationsListDialog.MigrationsListMode: self.setWindowTitle(self.tr("Available Migrations")) - self.migrationsList.setHeaderLabels([ - self.tr("Name"), - ]) + self.migrationsList.setHeaderLabels( + [ + self.tr("Name"), + ] + ) self.migrationsList.setSelectionMode( - QAbstractItemView.SelectionMode.ExtendedSelection) + QAbstractItemView.SelectionMode.ExtendedSelection + ) else: self.setWindowTitle(self.tr("Migrations Plan")) - self.migrationsList.setHeaderLabels([ - self.tr("Migration"), - self.tr("Dependencies"), - ]) + self.migrationsList.setHeaderLabels( + [ + self.tr("Migration"), + self.tr("Dependencies"), + ] + ) self.migrationsList.setSelectionMode( - QAbstractItemView.SelectionMode.SingleSelection) - + QAbstractItemView.SelectionMode.SingleSelection + ) + self.refreshButton = self.buttonBox.addButton( - self.tr("&Refresh"), QDialogButtonBox.ButtonRole.ActionRole) - self.refreshButton.setToolTip( - self.tr("Press to refresh the list")) + self.tr("&Refresh"), QDialogButtonBox.ButtonRole.ActionRole + ) + self.refreshButton.setToolTip(self.tr("Press to refresh the list")) self.refreshButton.setEnabled(False) - + @pyqtSlot(QAbstractButton) def on_buttonBox_clicked(self, button): """ Private slot called by a button of the button box clicked. - + @param button button that was clicked @type QAbstractButton """ - if button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Close - ): + if button == self.buttonBox.button(QDialogButtonBox.StandardButton.Close): self.close() - elif button == self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel - ): + elif button == self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel): self.__finish() elif button == self.refreshButton: self.on_refreshButton_clicked() - + def __finish(self): """ Private slot called when the process finished or the user pressed the button. """ if ( - self.proc is not None and - self.proc.state() != QProcess.ProcessState.NotRunning + self.proc is not None + and self.proc.state() != QProcess.ProcessState.NotRunning ): self.proc.terminate() QTimer.singleShot(2000, self.proc.kill) self.proc.waitForFinished(3000) - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setDefault(True) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setDefault(True) + self.refreshButton.setEnabled(True) - + self.__resizeColumns() - + def __procFinished(self, exitCode, exitStatus): """ Private slot connected to the finished signal. - + @param exitCode exit code of the process @type int @param exitStatus exit status of the process @type QProcess.ExitStatus """ self.__finish() - + def __resizeColumns(self): """ Private method to resize the list columns. """ self.migrationsList.header().resizeSections( - QHeaderView.ResizeMode.ResizeToContents) + QHeaderView.ResizeMode.ResizeToContents + ) if self.__mode == DjangoMigrationsListDialog.MigrationsListMode: self.migrationsList.header().setStretchLastSection(True) - + def start(self, pythonExecutable, sitePath, databaseName): """ Public slot used to start the process. - + @param pythonExecutable Python executable to be used @type str @param sitePath path of the site @@ -160,15 +165,15 @@ """ self.__pyExe = pythonExecutable self.__sitePath = sitePath - + self.errorGroup.hide() self.migrationsList.clear() - + self.__lastTopItem = None - + if sitePath: self.proc.setWorkingDirectory(sitePath) - + args = [] args.append("manage.py") args.append("showmigrations") @@ -180,45 +185,45 @@ args.append("2") if databaseName: args.append("--database={0}".format(databaseName)) - + self.proc.start(pythonExecutable, args) procStarted = self.proc.waitForStarted() if not procStarted: self.buttonBox.setFocus() EricMessageBox.critical( self, - self.tr('Process Generation Error'), + self.tr("Process Generation Error"), self.tr( - 'The process {0} could not be started. ' - 'Ensure, that it is in the search path.' - ).format(pythonExecutable)) + "The process {0} could not be started. " + "Ensure, that it is in the search path." + ).format(pythonExecutable), + ) return procStarted - + def __readStdout(self): """ Private slot to handle the readyReadStdout signal. - + It reads the output of the process, formats it and inserts it into the contents pane. """ while self.proc.canReadLine(): - s = str(self.proc.readLine(), self.ioEncoding, 'replace').rstrip() + s = str(self.proc.readLine(), self.ioEncoding, "replace").rstrip() if self.__mode == DjangoMigrationsListDialog.MigrationsListMode: self.__createListItem(s) else: self.__createPlanItem(s) - + def __createListItem(self, line): """ Private method to create an item for list mode. - + @param line line of text @type str """ if not line.startswith(" "): # application name - self.__lastTopItem = QTreeWidgetItem( - self.migrationsList, [line.strip()]) + self.__lastTopItem = QTreeWidgetItem(self.migrationsList, [line.strip()]) self.__lastTopItem.setExpanded(True) else: # migration name @@ -234,11 +239,11 @@ itm.setCheckState(0, Qt.CheckState.Unchecked) else: itm.setCheckState(0, Qt.CheckState.Checked) - + def __createPlanItem(self, line): """ Private method to create an item for plan mode. - + @param line line of text @type str """ @@ -246,63 +251,64 @@ applied = line[:3] parts = line[3:].strip().split(None, 2) if len(parts) == 3: - dependencies = "\n".join([ - d.strip() for d in parts[2].strip()[1:-1].split(",") - ]) - itm = QTreeWidgetItem(self.migrationsList, [ - parts[0].strip(), - dependencies, - ]) + dependencies = "\n".join( + [d.strip() for d in parts[2].strip()[1:-1].split(",")] + ) + itm = QTreeWidgetItem( + self.migrationsList, + [ + parts[0].strip(), + dependencies, + ], + ) else: - itm = QTreeWidgetItem(self.migrationsList, [ - parts[0].strip(), - "", - ]) + itm = QTreeWidgetItem( + self.migrationsList, + [ + parts[0].strip(), + "", + ], + ) if applied[1] != " ": itm.setCheckState(0, Qt.CheckState.Checked) - + def __readStderr(self): """ Private slot to handle the readyReadStderr signal. - + It reads the error output of the process and inserts it into the error pane. """ if self.proc is not None: self.errorGroup.show() - s = str(self.proc.readAllStandardError(), self.ioEncoding, - 'replace') + s = str(self.proc.readAllStandardError(), self.ioEncoding, "replace") self.errors.insertPlainText(s) self.errors.ensureCursorVisible() - + @pyqtSlot() def on_refreshButton_clicked(self): """ Private slot to refresh the log. """ - self.buttonBox.button( - QDialogButtonBox.StandardButton.Close).setEnabled(False) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setEnabled(True) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Cancel).setDefault(True) - + self.buttonBox.button(QDialogButtonBox.StandardButton.Close).setEnabled(False) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(True) + self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(True) + self.refreshButton.setEnabled(False) - + self.start(self.__pyExe, self.__sitePath) - + @pyqtSlot(QPoint) def on_migrationsList_customContextMenuRequested(self, pos): """ Private slot to show the context menu. - + @param pos position the context menu was requested at @type QPoint """ menu = QMenu(self.migrationsList) - menu.addAction(self.tr("Apply All Migrations"), - self.__applyAllMigrations) - + menu.addAction(self.tr("Apply All Migrations"), self.__applyAllMigrations) + if self.__mode == DjangoMigrationsListDialog.MigrationsListMode: selItems = self.migrationsList.selectedItems() if len(selItems) > 0: @@ -310,38 +316,39 @@ for itm in selItems: if itm.parent() is None: selApps.append(itm) - + menu.addAction( - self.tr("Apply Selected Migrations"), - self.__applyMigration).setEnabled(len(selItems) == 1) + self.tr("Apply Selected Migrations"), self.__applyMigration + ).setEnabled(len(selItems) == 1) menu.addAction( - self.tr("Unapply Migrations"), - self.__unapplyMigration).setEnabled(len(selApps) == 1) + self.tr("Unapply Migrations"), self.__unapplyMigration + ).setEnabled(len(selApps) == 1) menu.addSeparator() menu.addAction( - self.tr("Make Migrations"), - self.__makeMigrations).setEnabled(len(selApps) > 0) + self.tr("Make Migrations"), self.__makeMigrations + ).setEnabled(len(selApps) > 0) act = menu.addAction( self.tr("Make Empty Migrations"), - lambda: self.__makeMigrations(empty=True)) + lambda: self.__makeMigrations(empty=True), + ) act.setEnabled(len(selApps) > 0) act = menu.addAction( self.tr("Make Migrations (dry-run)"), - lambda: self.__makeMigrations(dryRun=True)) + lambda: self.__makeMigrations(dryRun=True), + ) act.setEnabled(len(selApps) > 0) else: - menu.addAction(self.tr("Apply Selected Migrations"), - self.__applyMigration) - + menu.addAction(self.tr("Apply Selected Migrations"), self.__applyMigration) + menu.popup(self.migrationsList.mapToGlobal(pos)) - + def __applyAllMigrations(self): """ Private slot to apply all migrations. """ self.__django.applyMigrations() self.on_refreshButton_clicked() - + def __applyMigration(self): """ Private slot to apply the selected migrations. @@ -357,11 +364,11 @@ app = itm.parent().text(0) else: app, migration = itm.text(0).split(".", 1) - + self.__django.applyMigrations(app=app, migration=migration) - + self.on_refreshButton_clicked() - + def __unapplyMigration(self): """ Private slot to unapply the selected migrations. @@ -372,13 +379,13 @@ # only valid for app entries app = itm.text(0) self.__django.applyMigrations(app=app, migration="zero") - + self.on_refreshButton_clicked() - + def __makeMigrations(self, dryRun=False, empty=False): """ Private slot to make migrations for the selected apps. - + @param dryRun flag indicating a dry-run @type bool @param empty flag indicating an empty migration @@ -388,17 +395,19 @@ for itm in self.migrationsList.selectedItems(): if itm.parent() is None: apps.append(itm.text(0)) - + if apps: migration, ok = QInputDialog.getText( self, self.tr("Make Migrations"), - self.tr("Enter a name for the migrations (leave empty to" - " use system supplied name):"), - QLineEdit.EchoMode.Normal) - + self.tr( + "Enter a name for the migrations (leave empty to" + " use system supplied name):" + ), + QLineEdit.EchoMode.Normal, + ) + if ok: - self.__django.makeMigrations(apps, migration, dryRun, empty, - True) - + self.__django.makeMigrations(apps, migration, dryRun, empty, True) + self.on_refreshButton_clicked()
--- a/ProjectDjango/DjangoRunTestServerDataDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoRunTestServerDataDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -23,10 +23,11 @@ """ Class implementing a dialog to enter the data for the 'loaddata' command. """ + def __init__(self, project, parent=None): """ Constructor - + @param project reference to the Django project object @type Project @param parent reference to the parent widget @@ -34,45 +35,44 @@ """ super().__init__(parent) self.setupUi(self) - + fileFilters = self.tr("JSON Files (*.json);;XML Files (*.xml);;") with contextlib.suppress(ImportError): - import yaml # __IGNORE_WARNING__ + import yaml # __IGNORE_WARNING__ + fileFilters += self.tr("YAML Files (*.yaml);;") fileFilters += self.tr("All Files (*)") - + self.fixturePicker.setMode(EricPathPickerModes.OPEN_FILE_MODE) self.fixturePicker.setFilters(fileFilters) - + self.fixtureFileButton.setIcon(UI.PixmapCache.getIcon("open")) - + self.__project = project - - self.buttonBox.button( - QDialogButtonBox.StandardButton.Ok).setEnabled(False) - + + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + @pyqtSlot(str) def on_fixturesPicker_textChanged(self, txt): """ Private slot to handle a change of the fixtures text. - + @param txt text of the line edit @type str """ - self.buttonBox.button( - QDialogButtonBox.StandardButton.Ok).setEnabled(bool(txt)) - + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(bool(txt)) + def getData(self): """ Public method to get the data entered into the dialog. - + @return list of fixtures @rtype list of str """ fixturesStr = self.fixturePicker.text() fixtures = fixturesStr.split() - + return fixtures
--- a/ProjectDjango/DjangoSendTestEmailDataDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoSendTestEmailDataDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -17,30 +17,29 @@ Class implementing a dialog to enter the data for the 'sendtestemail' command. """ + def __init__(self, parent=None): """ Constructor - + @param parent reference to the parent widget @type QWidget """ super().__init__(parent) self.setupUi(self) - + def getData(self): """ Public method to get the dialog data. - + @return tuple containing a flag indicating to send to the defined managers, a flag indicating to send to the defined administrators and a list of recipients @rtype tuple of (bool, bool, list of str) """ recipientsStr = self.recipientsEdit.toPlainText() - recipients = [r.strip() - for r in recipientsStr.splitlines() - if r.strip()] - + recipients = [r.strip() for r in recipientsStr.splitlines() if r.strip()] + return ( self.managersCheckBox.isChecked(), self.adminsCheckBox.isChecked(),
--- a/ProjectDjango/DjangoSquashMigrationSelectionDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoSquashMigrationSelectionDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -14,19 +14,21 @@ from PyQt6.QtWidgets import QDialog, QDialogButtonBox from .Ui_DjangoSquashMigrationSelectionDialog import ( - Ui_DjangoSquashMigrationSelectionDialog + Ui_DjangoSquashMigrationSelectionDialog, ) class DjangoSquashMigrationSelectionDialog( - QDialog, Ui_DjangoSquashMigrationSelectionDialog): + QDialog, Ui_DjangoSquashMigrationSelectionDialog +): """ Class implementing a dialog to enter data needed to squash migrations. """ + def __init__(self, migrations, django, suffix, parent=None): """ Constructor - + @param migrations dictionary containing the available migrations @type dict @param django reference to the Django project object @@ -38,42 +40,41 @@ """ super().__init__(parent) self.setupUi(self) - - self.__appliedIcon = QIcon(os.path.join( - os.path.dirname(__file__), "icons", "applied-{0}".format(suffix) - )) - + + self.__appliedIcon = QIcon( + os.path.join( + os.path.dirname(__file__), "icons", "applied-{0}".format(suffix) + ) + ) + self.__migrations = migrations - self.applicationComboBox.addItems( - [""] + sorted(self.__migrations.keys())) + self.applicationComboBox.addItems([""] + sorted(self.__migrations.keys())) self.on_applicationComboBox_activated("") - + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + def __updateOkButton(self): """ Private slot to set the enabled state of the OK button. """ - enabled = ( - bool(self.applicationComboBox.currentText()) and - bool(self.endMigrationComboBox.currentText())) - self.buttonBox.button( - QDialogButtonBox.StandardButton.Ok).setEnabled(enabled) - + enabled = bool(self.applicationComboBox.currentText()) and bool( + self.endMigrationComboBox.currentText() + ) + self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(enabled) + @pyqtSlot(str) def on_applicationComboBox_activated(self, app): """ Private slot to update the migrations combo boxes. - + @param app name of the selected application @type str """ self.startMigrationComboBox.clear() self.endMigrationComboBox.clear() if app: - for combo in [self.startMigrationComboBox, - self.endMigrationComboBox]: + for combo in [self.startMigrationComboBox, self.endMigrationComboBox]: combo.addItem("") for applied, migration in self.__migrations[app]: if applied: @@ -81,36 +82,36 @@ else: combo.addItem(migration) self.__updateOkButton() - + @pyqtSlot(str) def on_endMigrationComboBox_activated(self, migration): """ Private slot handling the selection of a migration. - + @param migration name of the selected migration @type str """ self.__updateOkButton() - + def getData(self): """ Public method to retrieve the data entered by the user. - + @return tuple containing the selected app, the start migration, the end migration and a flag indicating no optimization is wanted @rtype tuple of three str and a bool """ startMigration = ( self.startMigrationComboBox.currentText() - if self.startMigrationComboBox.isEnabled() else - "" + if self.startMigrationComboBox.isEnabled() + else "" ) name = self.nameEdit.text() if self.nameEdit.isEnabled() else "" - + return ( self.applicationComboBox.currentText(), startMigration, self.endMigrationComboBox.currentText(), self.noOptimizeCheckBox.isChecked(), - name + name, )
--- a/ProjectDjango/DjangoTestDataDialog.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/DjangoTestDataDialog.py Wed Sep 21 16:42:20 2022 +0200 @@ -16,10 +16,11 @@ """ Class implementing a dialog to enter some data for running tests. """ + def __init__(self, project, keepDatabases, parent=None): """ Constructor - + @param project reference to the Django project object @type Project @param keepDatabases flag indicating to set the keep databases @@ -30,25 +31,26 @@ """ super().__init__(parent) self.setupUi(self) - + self.__project = project - + self.labelsComboBox.addItems( - self.__project.getRecentTestData("RecentTestLabels")) - self.tagsComboBox.addItems( - self.__project.getRecentTestData("RecentTestTags")) + self.__project.getRecentTestData("RecentTestLabels") + ) + self.tagsComboBox.addItems(self.__project.getRecentTestData("RecentTestTags")) self.excludeTagsComboBox.addItems( - self.__project.getRecentTestData("RecentTestExcludeTags")) - + self.__project.getRecentTestData("RecentTestExcludeTags") + ) + self.keepCheckBox.setChecked(keepDatabases) - + msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) - + def getData(self): """ Public method to get the entered data. - + @return tuple containing a list of test labels, a test file pattern, a list of test tags, a list of test tags to be skipped, a flag indicating to keep the test database and a flag indicating to run @@ -59,16 +61,15 @@ labelsStr = self.labelsComboBox.currentText() self.__project.setMostRecentTestData("RecentTestLabels", labelsStr) labels = labelsStr.split() if labelsStr else [] - + tagsStr = self.tagsComboBox.currentText() self.__project.setMostRecentTestData("RecentTestTags", tagsStr) tags = tagsStr.split() if tagsStr else [] - + excludeTagsStr = self.excludeTagsComboBox.currentText() - self.__project.setMostRecentTestData("RecentTestExcludeTags", - excludeTagsStr) + self.__project.setMostRecentTestData("RecentTestExcludeTags", excludeTagsStr) excludeTags = excludeTagsStr.split() if excludeTagsStr else [] - + return ( labels, self.testFilePatternsEdit.text(),
--- a/ProjectDjango/Project.py Fri Dec 31 13:17:55 2021 +0100 +++ b/ProjectDjango/Project.py Wed Sep 21 16:42:20 2022 +0200 @@ -30,10 +30,11 @@ import UI.PixmapCache -class DjangoNoSiteSelectedException(Exception): +class DjangoNoSiteSelectedError(Exception): """ Exception thrown to signal, that there is no current site. """ + pass @@ -41,11 +42,12 @@ """ Class transforming the call arguments in case of gnome-terminal. """ + def start(self, cmd, args=None, mode=QIODeviceBase.OpenModeFlag.ReadWrite): """ Public method to start the given program (cmd) in a new process, if none is already running, passing the command line arguments in args. - + @param cmd start the given program cmd @type str @param args list of parameters @@ -55,24 +57,25 @@ """ if args is None: args = [] - + if ( - cmd.endswith(('gnome-terminal', 'konsole', 'xfce4-terminal', - 'mate-terminal')) and - '-e' in args + cmd.endswith( + ("gnome-terminal", "konsole", "xfce4-terminal", "mate-terminal") + ) + and "-e" in args ): - index = args.index('-e') + 1 - cargs = ' '.join(args[index:]) + index = args.index("-e") + 1 + cargs = " ".join(args[index:]) args[index:] = [cargs] - + super().start(cmd, args, mode) - + @staticmethod - def startDetached(cmd, args=None, path=''): + def startDetached(cmd, args=None, path=""): """ Public static method to start the given program (cmd) in a new process, if none is already running, passing the command line arguments in args. - + @param cmd start the given program cmd @type str @param args list of parameters @@ -84,16 +87,17 @@ """ if args is None: args = [] - + if ( - cmd.endswith(('gnome-terminal', 'konsole', 'xfce4-terminal', - 'mate-terminal')) and - '-e' in args + cmd.endswith( + ("gnome-terminal", "konsole", "xfce4-terminal", "mate-terminal") + ) + and "-e" in args ): - index = args.index('-e') + 1 - cargs = ' '.join(args[index:]) + index = args.index("-e") + 1 + cargs = " ".join(args[index:]) args[index:] = [cargs] - + return QProcessPyQt.startDetached(cmd, args, path) @@ -101,13 +105,14 @@ """ Class implementing the Django project support. """ + RecentApplicationsKey = "Django/RecentApplications" RecentDatabaseNamesKey = "Django/RecentDatabaseNames" - + def __init__(self, plugin, iconSuffix, parent=None): """ Constructor - + @param plugin reference to the plugin object @type ProjectDjangoPlugin @param iconSuffix suffix for the icons @@ -116,215 +121,251 @@ @type QObject """ super().__init__(parent) - + self.__plugin = plugin self.__iconSuffix = iconSuffix self.__ui = parent - + self.__ericProject = ericApp().getObject("Project") self.__virtualEnvManager = ericApp().getObject("VirtualEnvManager") self.__hooksInstalled = False - - self.__menus = {} # dictionary with references to menus - + + self.__menus = {} # dictionary with references to menus + self.__serverProc = None self.__testServerProc = None - + self.__recentApplications = [] self.__loadRecentApplications() - + self.__recentDatabaseNames = [] self.__loadRecentDatabaseNames() - + self.__recentTestData = { "RecentTestLabels": [], "RecentTestTags": [], "RecentTestExcludeTags": [], } self.__loadRecentTestData() - + def initActions(self): """ Public method to define the Django actions. """ self.actions = [] - + self.selectSiteAct = EricAction( - self.tr('Current Project'), - "", - 0, 0, - self, 'django_current_project') - self.selectSiteAct.setStatusTip(self.tr( - 'Selects the current project')) - self.selectSiteAct.setWhatsThis(self.tr( - """<b>Current Project</b>""" - """<p>Selects the current project. Used for multi-project """ - """Django projects to switch between the projects.</p>""" - )) + self.tr("Current Project"), "", 0, 0, self, "django_current_project" + ) + self.selectSiteAct.setStatusTip(self.tr("Selects the current project")) + self.selectSiteAct.setWhatsThis( + self.tr( + """<b>Current Project</b>""" + """<p>Selects the current project. Used for multi-project """ + """Django projects to switch between the projects.</p>""" + ) + ) self.selectSiteAct.triggered.connect(self.__selectSite) self.actions.append(self.selectSiteAct) self.__setCurrentSite(None) - + ############################## ## start actions below ## ############################## - + self.startProjectAct = EricAction( - self.tr('Start Project'), - self.tr('Start &Project'), - 0, 0, - self, 'django_start_project') - self.startProjectAct.setStatusTip(self.tr( - 'Starts a new Django project')) - self.startProjectAct.setWhatsThis(self.tr( - """<b>Start Project</b>""" - """<p>Starts a new Django project using "django-admin.py""" - """ startproject".</p>""" - )) + self.tr("Start Project"), + self.tr("Start &Project"), + 0, + 0, + self, + "django_start_project", + ) + self.startProjectAct.setStatusTip(self.tr("Starts a new Django project")) + self.startProjectAct.setWhatsThis( + self.tr( + """<b>Start Project</b>""" + """<p>Starts a new Django project using "django-admin.py""" + """ startproject".</p>""" + ) + ) self.startProjectAct.triggered.connect(self.__startProject) self.actions.append(self.startProjectAct) - + self.startGlobalApplicationAct = EricAction( - self.tr('Start Application (global)'), - self.tr('Start Application (&global)'), - 0, 0, - self, 'django_start_global_application') - self.startGlobalApplicationAct.setStatusTip(self.tr( - 'Starts a new global Django application')) - self.startGlobalApplicationAct.setWhatsThis(self.tr( - """<b>Start Application (global)</b>""" - """<p>Starts a new global Django application using""" - """ "django-admin.py startapp".</p>""" - )) - self.startGlobalApplicationAct.triggered.connect( - self.__startGlobalApplication) + self.tr("Start Application (global)"), + self.tr("Start Application (&global)"), + 0, + 0, + self, + "django_start_global_application", + ) + self.startGlobalApplicationAct.setStatusTip( + self.tr("Starts a new global Django application") + ) + self.startGlobalApplicationAct.setWhatsThis( + self.tr( + """<b>Start Application (global)</b>""" + """<p>Starts a new global Django application using""" + """ "django-admin.py startapp".</p>""" + ) + ) + self.startGlobalApplicationAct.triggered.connect(self.__startGlobalApplication) self.actions.append(self.startGlobalApplicationAct) - + self.startLocalApplicationAct = EricAction( - self.tr('Start Application (local)'), - self.tr('Start Application (&local)'), - 0, 0, - self, 'django_start_local_application') - self.startLocalApplicationAct.setStatusTip(self.tr( - 'Starts a new local Django application')) - self.startLocalApplicationAct.setWhatsThis(self.tr( - """<b>Start Application (local)</b>""" - """<p>Starts a new local Django application using""" - """ "manage.py startapp".</p>""" - )) - self.startLocalApplicationAct.triggered.connect( - self.__startLocalApplication) + self.tr("Start Application (local)"), + self.tr("Start Application (&local)"), + 0, + 0, + self, + "django_start_local_application", + ) + self.startLocalApplicationAct.setStatusTip( + self.tr("Starts a new local Django application") + ) + self.startLocalApplicationAct.setWhatsThis( + self.tr( + """<b>Start Application (local)</b>""" + """<p>Starts a new local Django application using""" + """ "manage.py startapp".</p>""" + ) + ) + self.startLocalApplicationAct.triggered.connect(self.__startLocalApplication) self.actions.append(self.startLocalApplicationAct) - + ############################## ## run actions below ## ############################## - + self.runServerAct = EricAction( - self.tr('Run Server'), - self.tr('Run &Server'), - 0, 0, - self, 'django_run_server') - self.runServerAct.setStatusTip(self.tr( - 'Starts the Django Web server')) - self.runServerAct.setWhatsThis(self.tr( - """<b>Run Server</b>""" - """<p>Starts the Django Web server using "manage.py""" - """ runserver".</p>""" - )) + self.tr("Run Server"), + self.tr("Run &Server"), + 0, + 0, + self, + "django_run_server", + ) + self.runServerAct.setStatusTip(self.tr("Starts the Django Web server")) + self.runServerAct.setWhatsThis( + self.tr( + """<b>Run Server</b>""" + """<p>Starts the Django Web server using "manage.py""" + """ runserver".</p>""" + ) + ) self.runServerAct.triggered.connect(self.__runServer) self.actions.append(self.runServerAct) - + self.runBrowserAct = EricAction( - self.tr('Run Web-Browser'), - self.tr('Run &Web-Browser'), - 0, 0, - self, 'django_run_browser') - self.runBrowserAct.setStatusTip(self.tr( - 'Starts the default Web-Browser with the URL of the Django Web' - ' server')) - self.runBrowserAct.setWhatsThis(self.tr( - """<b>Run Web-Browser</b>""" - """<p>Starts the default Web-Browser with the URL of the """ - """Django Web server.</p>""" - )) + self.tr("Run Web-Browser"), + self.tr("Run &Web-Browser"), + 0, + 0, + self, + "django_run_browser", + ) + self.runBrowserAct.setStatusTip( + self.tr( + "Starts the default Web-Browser with the URL of the Django Web" + " server" + ) + ) + self.runBrowserAct.setWhatsThis( + self.tr( + """<b>Run Web-Browser</b>""" + """<p>Starts the default Web-Browser with the URL of the """ + """Django Web server.</p>""" + ) + ) self.runBrowserAct.triggered.connect(self.__runBrowser) self.actions.append(self.runBrowserAct) - + ############################## ## caching actions below ## ############################## - + self.createCacheTableAct = EricAction( - self.tr('Create Cache Tables'), - self.tr('C&reate Cache Tables'), - 0, 0, - self, 'django_create_cache_tables') - self.createCacheTableAct.setStatusTip(self.tr( - 'Creates the tables needed to use the SQL cache backend')) - self.createCacheTableAct.setWhatsThis(self.tr( - """<b>Create Cache Tables</b>""" - """<p>Creates the tables needed to use the SQL cache""" - """ backend.</p>""" - )) - self.createCacheTableAct.triggered.connect( - self.__createCacheTables) + self.tr("Create Cache Tables"), + self.tr("C&reate Cache Tables"), + 0, + 0, + self, + "django_create_cache_tables", + ) + self.createCacheTableAct.setStatusTip( + self.tr("Creates the tables needed to use the SQL cache backend") + ) + self.createCacheTableAct.setWhatsThis( + self.tr( + """<b>Create Cache Tables</b>""" + """<p>Creates the tables needed to use the SQL cache""" + """ backend.</p>""" + ) + ) + self.createCacheTableAct.triggered.connect(self.__createCacheTables) self.actions.append(self.createCacheTableAct) - + ############################## ## help action below ## ############################## - + self.helpAct = EricAction( - self.tr('Help'), - self.tr('&Help'), - 0, 0, - self, 'django_help') - self.helpAct.setStatusTip(self.tr( - 'Shows the Django help index')) - self.helpAct.setWhatsThis(self.tr( - """<b>Help</b>""" - """<p>Shows the Django help index page.</p>""" - )) + self.tr("Help"), self.tr("&Help"), 0, 0, self, "django_help" + ) + self.helpAct.setStatusTip(self.tr("Shows the Django help index")) + self.helpAct.setWhatsThis( + self.tr("""<b>Help</b>""" """<p>Shows the Django help index page.</p>""") + ) self.helpAct.triggered.connect(self.__showHelpIndex) self.actions.append(self.helpAct) - + ############################## ## about action below ## ############################## - + self.aboutDjangoAct = EricAction( - self.tr('About Django'), - self.tr('About D&jango'), - 0, 0, - self, 'django_about') - self.aboutDjangoAct.setStatusTip(self.tr( - 'Shows some information about Django')) - self.aboutDjangoAct.setWhatsThis(self.tr( - """<b>About Django</b>""" - """<p>Shows some information about Django.</p>""" - )) + self.tr("About Django"), + self.tr("About D&jango"), + 0, + 0, + self, + "django_about", + ) + self.aboutDjangoAct.setStatusTip(self.tr("Shows some information about Django")) + self.aboutDjangoAct.setWhatsThis( + self.tr( + """<b>About Django</b>""" + """<p>Shows some information about Django.</p>""" + ) + ) self.aboutDjangoAct.triggered.connect(self.__djangoInfo) self.actions.append(self.aboutDjangoAct) - + ############################## ## check action below ## ############################## - + self.checkAct = EricAction( - self.tr('Check Project'), - self.tr('Check Project'), - 0, 0, - self, 'django_check_project') - self.checkAct.setStatusTip(self.tr( - 'Inspects the Django project for common problems')) - self.checkAct.setWhatsThis(self.tr( - """<b>Check Project</b>""" - """<p>This inspects the Django project for common problems.</p>""" - )) + self.tr("Check Project"), + self.tr("Check Project"), + 0, + 0, + self, + "django_check_project", + ) + self.checkAct.setStatusTip( + self.tr("Inspects the Django project for common problems") + ) + self.checkAct.setWhatsThis( + self.tr( + """<b>Check Project</b>""" + """<p>This inspects the Django project for common problems.</p>""" + ) + ) self.checkAct.triggered.connect(self.__performCheck) self.actions.append(self.checkAct) - + self.__initDatabaseActions() self.__initDatabaseSqlActions() self.__initMigrationActions() @@ -338,435 +379,566 @@ Private method to define the database related actions. """ self.selectDatabaseNameAct = EricAction( - self.tr('Current Database'), - "", - 0, 0, - self, 'django_current_database') - self.selectDatabaseNameAct.setStatusTip(self.tr( - 'Selects the current database')) - self.selectDatabaseNameAct.setWhatsThis(self.tr( - """<b>Current Database</b>""" - """<p>Selects the database name to be used by all database""" - """ actions. An empty database name indicates to use the default""" - """ name.</p>""" - )) + self.tr("Current Database"), "", 0, 0, self, "django_current_database" + ) + self.selectDatabaseNameAct.setStatusTip(self.tr("Selects the current database")) + self.selectDatabaseNameAct.setWhatsThis( + self.tr( + """<b>Current Database</b>""" + """<p>Selects the database name to be used by all database""" + """ actions. An empty database name indicates to use the default""" + """ name.</p>""" + ) + ) self.selectDatabaseNameAct.triggered.connect(self.__selectDatabaseName) self.actions.append(self.selectDatabaseNameAct) self.__setCurrentDatabase(None) - + self.inspectDatabaseAct = EricAction( - self.tr('Introspect'), - self.tr('&Introspect'), - 0, 0, - self, 'django_database_inspect') - self.inspectDatabaseAct.setStatusTip(self.tr( - 'Introspects the database tables and outputs a Django model' - ' module')) - self.inspectDatabaseAct.setWhatsThis(self.tr( - """<b>Introspect</b>""" - """<p>Introspects the database tables and outputs a """ - """Django model module.</p>""" - )) + self.tr("Introspect"), + self.tr("&Introspect"), + 0, + 0, + self, + "django_database_inspect", + ) + self.inspectDatabaseAct.setStatusTip( + self.tr( + "Introspects the database tables and outputs a Django model" " module" + ) + ) + self.inspectDatabaseAct.setWhatsThis( + self.tr( + """<b>Introspect</b>""" + """<p>Introspects the database tables and outputs a """ + """Django model module.</p>""" + ) + ) self.inspectDatabaseAct.triggered.connect(self.__databaseInspect) self.actions.append(self.inspectDatabaseAct) - + self.flushDatabaseAct = EricAction( - self.tr('Flush'), - self.tr('&Flush'), - 0, 0, - self, 'django_database_flush') - self.flushDatabaseAct.setStatusTip(self.tr( - 'Returns all database tables to the state just after their' - ' installation')) - self.flushDatabaseAct.setWhatsThis(self.tr( - """<b>Flush</b>""" - """<p>Returns all database tables to the state """ - """just after their installation.</p>""" - )) + self.tr("Flush"), self.tr("&Flush"), 0, 0, self, "django_database_flush" + ) + self.flushDatabaseAct.setStatusTip( + self.tr( + "Returns all database tables to the state just after their" + " installation" + ) + ) + self.flushDatabaseAct.setWhatsThis( + self.tr( + """<b>Flush</b>""" + """<p>Returns all database tables to the state """ + """just after their installation.</p>""" + ) + ) self.flushDatabaseAct.triggered.connect(self.__databaseFlush) self.actions.append(self.flushDatabaseAct) - + self.databaseClientAct = EricAction( - self.tr('Start Client Console'), - self.tr('Start &Client Console'), - 0, 0, - self, 'django_database_client') - self.databaseClientAct.setStatusTip(self.tr( - 'Starts a console window for the database client')) - self.databaseClientAct.setWhatsThis(self.tr( - """<b>Start Client Console</b>""" - """<p>Starts a console window for the database client.</p>""" - )) + self.tr("Start Client Console"), + self.tr("Start &Client Console"), + 0, + 0, + self, + "django_database_client", + ) + self.databaseClientAct.setStatusTip( + self.tr("Starts a console window for the database client") + ) + self.databaseClientAct.setWhatsThis( + self.tr( + """<b>Start Client Console</b>""" + """<p>Starts a console window for the database client.</p>""" + ) + ) self.databaseClientAct.triggered.connect(self.__runDatabaseClient) self.actions.append(self.databaseClientAct) - + def __initDatabaseSqlActions(self): """ Private method to define the database SQL related actions. """ self.databaseSqlFlushAct = EricAction( - self.tr('Flush Database'), - self.tr('&Flush Database'), - 0, 0, - self, 'django_database_sql_flush_database') - self.databaseSqlFlushAct.setStatusTip(self.tr( - 'Prints a list of statements to return all database tables to the' - ' state just after their installation')) - self.databaseSqlFlushAct.setWhatsThis(self.tr( - """<b>Flush Database</b>""" - """<p>Prints a list of statements to return all database tables""" - """ to the state just after their installation.</p>""" - )) - self.databaseSqlFlushAct.triggered.connect( - self.__databaseSqlFlushDatabase) + self.tr("Flush Database"), + self.tr("&Flush Database"), + 0, + 0, + self, + "django_database_sql_flush_database", + ) + self.databaseSqlFlushAct.setStatusTip( + self.tr( + "Prints a list of statements to return all database tables to the" + " state just after their installation" + ) + ) + self.databaseSqlFlushAct.setWhatsThis( + self.tr( + """<b>Flush Database</b>""" + """<p>Prints a list of statements to return all database tables""" + """ to the state just after their installation.</p>""" + ) + ) + self.databaseSqlFlushAct.triggered.connect(self.__databaseSqlFlushDatabase) self.actions.append(self.databaseSqlFlushAct) - + self.databaseSqlResetSeqAct = EricAction( - self.tr('Reset Sequences'), - self.tr('Reset &Sequences'), - 0, 0, - self, 'django_database_sql_reset_sequences') - self.databaseSqlResetSeqAct.setStatusTip(self.tr( - 'Prints the SQL statements for resetting sequences for ' - 'one or more applications')) - self.databaseSqlResetSeqAct.setWhatsThis(self.tr( - """<b>Reset Sequences</b>""" - """<p>Prints the SQL statements for resetting sequences for """ - """one or more applications.</p>""" - )) - self.databaseSqlResetSeqAct.triggered.connect( - self.__databaseSqlResetSequences) + self.tr("Reset Sequences"), + self.tr("Reset &Sequences"), + 0, + 0, + self, + "django_database_sql_reset_sequences", + ) + self.databaseSqlResetSeqAct.setStatusTip( + self.tr( + "Prints the SQL statements for resetting sequences for " + "one or more applications" + ) + ) + self.databaseSqlResetSeqAct.setWhatsThis( + self.tr( + """<b>Reset Sequences</b>""" + """<p>Prints the SQL statements for resetting sequences for """ + """one or more applications.</p>""" + ) + ) + self.databaseSqlResetSeqAct.triggered.connect(self.__databaseSqlResetSequences) self.actions.append(self.databaseSqlResetSeqAct) - + self.databaseSqlMigrateAct = EricAction( - self.tr('Apply Migration'), - self.tr('&Apply Migration'), - 0, 0, - self, 'django_database_sql_apply_migration') - self.databaseSqlMigrateAct.setStatusTip(self.tr( - 'Prints the SQL statements to apply a migration of an' - ' application')) - self.databaseSqlMigrateAct.setWhatsThis(self.tr( - """<b>Apply Migration</b>""" - """<p>Prints the SQL statements to apply a migration of an""" - """ application.</p>""" - )) - self.databaseSqlMigrateAct.triggered.connect( - self.__databaseSqlMigrate) + self.tr("Apply Migration"), + self.tr("&Apply Migration"), + 0, + 0, + self, + "django_database_sql_apply_migration", + ) + self.databaseSqlMigrateAct.setStatusTip( + self.tr( + "Prints the SQL statements to apply a migration of an" " application" + ) + ) + self.databaseSqlMigrateAct.setWhatsThis( + self.tr( + """<b>Apply Migration</b>""" + """<p>Prints the SQL statements to apply a migration of an""" + """ application.</p>""" + ) + ) + self.databaseSqlMigrateAct.triggered.connect(self.__databaseSqlMigrate) self.actions.append(self.databaseSqlMigrateAct) - + self.databaseSqlMigrateBackwardsAct = EricAction( - self.tr('Unapply Migration'), - self.tr('&Unapply Migration'), - 0, 0, - self, 'django_database_sql_unapply_migration') - self.databaseSqlMigrateBackwardsAct.setStatusTip(self.tr( - 'Prints the SQL statements to unapply a migration of an' - ' application')) - self.databaseSqlMigrateBackwardsAct.setWhatsThis(self.tr( - """<b>Unapply Migration</b>""" - """<p>Prints the SQL statements to unapply a migration of an""" - """ application.</p>""" - )) + self.tr("Unapply Migration"), + self.tr("&Unapply Migration"), + 0, + 0, + self, + "django_database_sql_unapply_migration", + ) + self.databaseSqlMigrateBackwardsAct.setStatusTip( + self.tr( + "Prints the SQL statements to unapply a migration of an" " application" + ) + ) + self.databaseSqlMigrateBackwardsAct.setWhatsThis( + self.tr( + """<b>Unapply Migration</b>""" + """<p>Prints the SQL statements to unapply a migration of an""" + """ application.</p>""" + ) + ) self.databaseSqlMigrateBackwardsAct.triggered.connect( - lambda: self.__databaseSqlMigrate(backwards=True)) + lambda: self.__databaseSqlMigrate(backwards=True) + ) self.actions.append(self.databaseSqlMigrateBackwardsAct) - + def __initToolsActions(self): """ Private method to define the tool actions. """ self.diffSettingsAct = EricAction( - self.tr('Diff Settings'), - self.tr('&Diff Settings'), - 0, 0, - self, 'django_tools_diffsettings') - self.diffSettingsAct.setStatusTip(self.tr( - 'Shows the modification made to the settings')) - self.diffSettingsAct.setWhatsThis(self.tr( - """<b>Diff Settings</b>""" - """<p>Shows the modification made to the settings.</p>""" - )) + self.tr("Diff Settings"), + self.tr("&Diff Settings"), + 0, + 0, + self, + "django_tools_diffsettings", + ) + self.diffSettingsAct.setStatusTip( + self.tr("Shows the modification made to the settings") + ) + self.diffSettingsAct.setWhatsThis( + self.tr( + """<b>Diff Settings</b>""" + """<p>Shows the modification made to the settings.</p>""" + ) + ) self.diffSettingsAct.triggered.connect(self.__diffSettings) self.actions.append(self.diffSettingsAct) - + self.runPythonShellAct = EricAction( - self.tr('Start Python Console'), - self.tr('Start &Python Console'), - 0, 0, - self, 'django_tools_pythonconsole') - self.runPythonShellAct.setStatusTip(self.tr( - 'Starts a Python interactive interpreter')) - self.runPythonShellAct.setWhatsThis(self.tr( - """<b>Start Python Console</b>""" - """<p>Starts a Python interactive interpreter.</p>""" - )) + self.tr("Start Python Console"), + self.tr("Start &Python Console"), + 0, + 0, + self, + "django_tools_pythonconsole", + ) + self.runPythonShellAct.setStatusTip( + self.tr("Starts a Python interactive interpreter") + ) + self.runPythonShellAct.setWhatsThis( + self.tr( + """<b>Start Python Console</b>""" + """<p>Starts a Python interactive interpreter.</p>""" + ) + ) self.runPythonShellAct.triggered.connect(self.__runPythonShell) self.actions.append(self.runPythonShellAct) - + self.testEmailAct = EricAction( - self.tr('Send Test Email'), - self.tr('Send Test &Email'), - 0, 0, - self, 'django_tools_sendtestemail') - self.testEmailAct.setStatusTip(self.tr( - 'Send a test email through Django')) - self.testEmailAct.setWhatsThis(self.tr( - """<b>Send Test Email</b>""" - """<p>Sends a test email to confirm email sending through Django""" - """ is working.</p>""" - )) + self.tr("Send Test Email"), + self.tr("Send Test &Email"), + 0, + 0, + self, + "django_tools_sendtestemail", + ) + self.testEmailAct.setStatusTip(self.tr("Send a test email through Django")) + self.testEmailAct.setWhatsThis( + self.tr( + """<b>Send Test Email</b>""" + """<p>Sends a test email to confirm email sending through Django""" + """ is working.</p>""" + ) + ) self.testEmailAct.triggered.connect(self.__sendTestEmail) self.actions.append(self.testEmailAct) - + def __initTestingActions(self): """ Private method to define the testing actions. """ self.dumpDataAct = EricAction( - self.tr('Dump Data'), - self.tr('&Dump Data'), - 0, 0, - self, 'django_tools_dumpdata') - self.dumpDataAct.setStatusTip(self.tr( - 'Dump the database data to a fixture')) - self.dumpDataAct.setWhatsThis(self.tr( - """<b>Dump Data</b>""" - """<p>Dump the database data to a fixture.</p>""" - )) + self.tr("Dump Data"), + self.tr("&Dump Data"), + 0, + 0, + self, + "django_tools_dumpdata", + ) + self.dumpDataAct.setStatusTip(self.tr("Dump the database data to a fixture")) + self.dumpDataAct.setWhatsThis( + self.tr( + """<b>Dump Data</b>""" """<p>Dump the database data to a fixture.</p>""" + ) + ) self.dumpDataAct.triggered.connect(self.__dumpData) self.actions.append(self.dumpDataAct) - + self.loadDataAct = EricAction( - self.tr('Load Data'), - self.tr('&Load Data'), - 0, 0, - self, 'django_tools_loaddata') - self.loadDataAct.setStatusTip(self.tr( - 'Load data from fixture files')) - self.loadDataAct.setWhatsThis(self.tr( - """<b>Load Data</b>""" - """<p>Load data from fixture files.</p>""" - )) + self.tr("Load Data"), + self.tr("&Load Data"), + 0, + 0, + self, + "django_tools_loaddata", + ) + self.loadDataAct.setStatusTip(self.tr("Load data from fixture files")) + self.loadDataAct.setWhatsThis( + self.tr("""<b>Load Data</b>""" """<p>Load data from fixture files.</p>""") + ) self.loadDataAct.triggered.connect(self.__loadData) self.actions.append(self.loadDataAct) - + self.runTestAct = EricAction( - self.tr('Run Testsuite'), - self.tr('Run &Testsuite'), - 0, 0, - self, 'django_tools_run_test') - self.runTestAct.setStatusTip(self.tr( - 'Run the test suite for applications or the whole site')) - self.runTestAct.setWhatsThis(self.tr( - """<b>Run Testsuite</b>""" - """<p>Run the test suite for applications or the whole site.</p>""" - )) + self.tr("Run Testsuite"), + self.tr("Run &Testsuite"), + 0, + 0, + self, + "django_tools_run_test", + ) + self.runTestAct.setStatusTip( + self.tr("Run the test suite for applications or the whole site") + ) + self.runTestAct.setWhatsThis( + self.tr( + """<b>Run Testsuite</b>""" + """<p>Run the test suite for applications or the whole site.</p>""" + ) + ) self.runTestAct.triggered.connect(self.__runTestSuite) self.actions.append(self.runTestAct) - + self.runDeprecationTestAct = EricAction( - self.tr('Run Testsuite (-Wall)'), - self.tr('Run Testsuite (-Wall)'), - 0, 0, - self, 'django_tools_run_deprecation_test') - self.runDeprecationTestAct.setStatusTip(self.tr( - 'Run the test suite for applications or the whole site with' - ' activated deprecation warnings')) - self.runDeprecationTestAct.setWhatsThis(self.tr( - """<b>Run Testsuite (-Wall)</b>""" - """<p>Run the test suite for applications or the whole site""" - """ with activated deprecation warnings.</p>""" - )) + self.tr("Run Testsuite (-Wall)"), + self.tr("Run Testsuite (-Wall)"), + 0, + 0, + self, + "django_tools_run_deprecation_test", + ) + self.runDeprecationTestAct.setStatusTip( + self.tr( + "Run the test suite for applications or the whole site with" + " activated deprecation warnings" + ) + ) + self.runDeprecationTestAct.setWhatsThis( + self.tr( + """<b>Run Testsuite (-Wall)</b>""" + """<p>Run the test suite for applications or the whole site""" + """ with activated deprecation warnings.</p>""" + ) + ) self.runDeprecationTestAct.triggered.connect( - lambda: self.__runTestSuite(deprecation=True)) + lambda: self.__runTestSuite(deprecation=True) + ) self.actions.append(self.runDeprecationTestAct) - + self.runTestServerAct = EricAction( - self.tr('Run Testserver'), - self.tr('Run Test&server'), - 0, 0, - self, 'django_tools_run_test_server') - self.runTestServerAct.setStatusTip(self.tr( - 'Run a development server with data from a set of fixtures')) - self.runTestServerAct.setWhatsThis(self.tr( - """<b>Run Testserver</b>""" - """<p>Run a development server with data from a set of""" - """ fixtures.</p>""" - )) + self.tr("Run Testserver"), + self.tr("Run Test&server"), + 0, + 0, + self, + "django_tools_run_test_server", + ) + self.runTestServerAct.setStatusTip( + self.tr("Run a development server with data from a set of fixtures") + ) + self.runTestServerAct.setWhatsThis( + self.tr( + """<b>Run Testserver</b>""" + """<p>Run a development server with data from a set of""" + """ fixtures.</p>""" + ) + ) self.runTestServerAct.triggered.connect(self.__runTestServer) self.actions.append(self.runTestServerAct) - + def __initAuthorizationActions(self): """ Private method to define the authorization actions. """ self.changePasswordAct = EricAction( - self.tr('Change Password'), - self.tr('Change &Password'), - 0, 0, - self, 'django_auth_changepassword') - self.changePasswordAct.setStatusTip(self.tr( - 'Change the password of a user')) - self.changePasswordAct.setWhatsThis(self.tr( - """<b>Change Password</b>""" - """<p>Change the password of a user of the Django project.</p>""" - )) + self.tr("Change Password"), + self.tr("Change &Password"), + 0, + 0, + self, + "django_auth_changepassword", + ) + self.changePasswordAct.setStatusTip(self.tr("Change the password of a user")) + self.changePasswordAct.setWhatsThis( + self.tr( + """<b>Change Password</b>""" + """<p>Change the password of a user of the Django project.</p>""" + ) + ) self.changePasswordAct.triggered.connect(self.__changePassword) self.actions.append(self.changePasswordAct) - + self.createSuperUserAct = EricAction( - self.tr('Create Superuser'), - self.tr('Create &Superuser'), - 0, 0, - self, 'django_auth_createsuperuser') - self.createSuperUserAct.setStatusTip(self.tr( - 'Create a superuser account')) - self.createSuperUserAct.setWhatsThis(self.tr( - """<b>Create Superuser</b>""" - """<p>Create a superuser account for the Django project.</p>""" - )) + self.tr("Create Superuser"), + self.tr("Create &Superuser"), + 0, + 0, + self, + "django_auth_createsuperuser", + ) + self.createSuperUserAct.setStatusTip(self.tr("Create a superuser account")) + self.createSuperUserAct.setWhatsThis( + self.tr( + """<b>Create Superuser</b>""" + """<p>Create a superuser account for the Django project.</p>""" + ) + ) self.createSuperUserAct.triggered.connect(self.__createSuperUser) self.actions.append(self.createSuperUserAct) - + def __initSessionActions(self): """ Private method to define the session actions. """ self.clearSessionsAct = EricAction( - self.tr('Clear Sessions'), - self.tr('Clear &Sessions'), - 0, 0, - self, 'django_session_clearsessions') - self.clearSessionsAct.setStatusTip(self.tr( - 'Clear expired sessions')) - self.clearSessionsAct.setWhatsThis(self.tr( - """<b>Clear Sessions</b>""" - """<p>Clear expired sessions of the Django project.</p>""" - )) + self.tr("Clear Sessions"), + self.tr("Clear &Sessions"), + 0, + 0, + self, + "django_session_clearsessions", + ) + self.clearSessionsAct.setStatusTip(self.tr("Clear expired sessions")) + self.clearSessionsAct.setWhatsThis( + self.tr( + """<b>Clear Sessions</b>""" + """<p>Clear expired sessions of the Django project.</p>""" + ) + ) self.clearSessionsAct.triggered.connect(self.__clearSessions) self.actions.append(self.clearSessionsAct) - + def __initMigrationActions(self): """ Private method to define the migration actions. """ self.showMigrationsAct = EricAction( - self.tr('Show Migrations'), - self.tr('&Show Migrations'), - 0, 0, - self, 'django_migration_show') - self.showMigrationsAct.setStatusTip(self.tr( - 'Show a list of available migrations')) - self.showMigrationsAct.setWhatsThis(self.tr( - """<b>Show Migrations</b>""" - """<p>This shows a list of available migrations of the Django""" - """ project and their status.</p>""" - )) + self.tr("Show Migrations"), + self.tr("&Show Migrations"), + 0, + 0, + self, + "django_migration_show", + ) + self.showMigrationsAct.setStatusTip( + self.tr("Show a list of available migrations") + ) + self.showMigrationsAct.setWhatsThis( + self.tr( + """<b>Show Migrations</b>""" + """<p>This shows a list of available migrations of the Django""" + """ project and their status.</p>""" + ) + ) self.showMigrationsAct.triggered.connect(self.__showMigrationsList) self.actions.append(self.showMigrationsAct) - + self.showMigrationsPlanAct = EricAction( - self.tr('Show Migrations Plan'), - self.tr('Show Migrations &Plan'), - 0, 0, - self, 'django_migration_show_plan') - self.showMigrationsPlanAct.setStatusTip(self.tr( - 'Show a list with the migrations plan')) - self.showMigrationsPlanAct.setWhatsThis(self.tr( - """<b>Show Migrations Plan</b>""" - """<p>This shows a list with the migrations plan of the Django""" - """ project.</p>""" - )) + self.tr("Show Migrations Plan"), + self.tr("Show Migrations &Plan"), + 0, + 0, + self, + "django_migration_show_plan", + ) + self.showMigrationsPlanAct.setStatusTip( + self.tr("Show a list with the migrations plan") + ) + self.showMigrationsPlanAct.setWhatsThis( + self.tr( + """<b>Show Migrations Plan</b>""" + """<p>This shows a list with the migrations plan of the Django""" + """ project.</p>""" + ) + ) self.showMigrationsPlanAct.triggered.connect(self.__showMigrationsPlan) self.actions.append(self.showMigrationsPlanAct) - + self.migrateAllAct = EricAction( - self.tr('Apply All Migrations'), - self.tr('&Apply All Migrations'), - 0, 0, - self, 'django_migration_apply_all') - self.migrateAllAct.setStatusTip(self.tr( - 'Apply all available migrations')) - self.migrateAllAct.setWhatsThis(self.tr( - """<b>Apply All Migrations</b>""" - """<p>This applies all migrations of the Django project.</p>""" - )) + self.tr("Apply All Migrations"), + self.tr("&Apply All Migrations"), + 0, + 0, + self, + "django_migration_apply_all", + ) + self.migrateAllAct.setStatusTip(self.tr("Apply all available migrations")) + self.migrateAllAct.setWhatsThis( + self.tr( + """<b>Apply All Migrations</b>""" + """<p>This applies all migrations of the Django project.</p>""" + ) + ) self.migrateAllAct.triggered.connect(self.__applyAllMigrations) self.actions.append(self.migrateAllAct) - + self.migrateSelectedAct = EricAction( - self.tr('Apply Selected Migrations'), - self.tr('Apply Selected Migrations'), - 0, 0, - self, 'django_migration_apply_selected') - self.migrateSelectedAct.setStatusTip(self.tr( - 'Apply selected migrations')) - self.migrateSelectedAct.setWhatsThis(self.tr( - """<b>Apply Selected Migrations</b>""" - """<p>This applies selected migrations of the Django""" - """ project.</p>""" - )) - self.migrateSelectedAct.triggered.connect( - self.__applySelectedMigrations) + self.tr("Apply Selected Migrations"), + self.tr("Apply Selected Migrations"), + 0, + 0, + self, + "django_migration_apply_selected", + ) + self.migrateSelectedAct.setStatusTip(self.tr("Apply selected migrations")) + self.migrateSelectedAct.setWhatsThis( + self.tr( + """<b>Apply Selected Migrations</b>""" + """<p>This applies selected migrations of the Django""" + """ project.</p>""" + ) + ) + self.migrateSelectedAct.triggered.connect(self.__applySelectedMigrations) self.actions.append(self.migrateSelectedAct) - + self.unmigrateAct = EricAction( - self.tr('Unapply Migrations'), - self.tr('&Unapply Migrations'), - 0, 0, - self, 'django_migration_unapply') - self.unmigrateAct.setStatusTip(self.tr( - 'Unapply all migrations for an app')) - self.unmigrateAct.setWhatsThis(self.tr( - """<b>Unapply Migrations</b>""" - """<p>This unapplies all migrations for an app of the Django""" - """ project.</p>""" - )) + self.tr("Unapply Migrations"), + self.tr("&Unapply Migrations"), + 0, + 0, + self, + "django_migration_unapply", + ) + self.unmigrateAct.setStatusTip(self.tr("Unapply all migrations for an app")) + self.unmigrateAct.setWhatsThis( + self.tr( + """<b>Unapply Migrations</b>""" + """<p>This unapplies all migrations for an app of the Django""" + """ project.</p>""" + ) + ) self.unmigrateAct.triggered.connect(self.__unapplyMigrations) self.actions.append(self.unmigrateAct) - + self.makeMigrationsAct = EricAction( - self.tr('Make Migrations'), - self.tr('&Make Migrations'), - 0, 0, - self, 'django_migration_make') - self.makeMigrationsAct.setStatusTip(self.tr( - 'Generate migrations for the project')) - self.makeMigrationsAct.setWhatsThis(self.tr( - """<b>Make Migrations</b>""" - """<p>This generates migrations for the Django project.</p>""" - )) + self.tr("Make Migrations"), + self.tr("&Make Migrations"), + 0, + 0, + self, + "django_migration_make", + ) + self.makeMigrationsAct.setStatusTip( + self.tr("Generate migrations for the project") + ) + self.makeMigrationsAct.setWhatsThis( + self.tr( + """<b>Make Migrations</b>""" + """<p>This generates migrations for the Django project.</p>""" + ) + ) self.makeMigrationsAct.triggered.connect(self.__makeMigrations) self.actions.append(self.makeMigrationsAct) - + self.squashMigrationsAct = EricAction( - self.tr('Squash Migrations'), - self.tr('S&quash Migrations'), - 0, 0, - self, 'django_migration_squash') - self.squashMigrationsAct.setStatusTip(self.tr( - 'Squash migrations of an application of the project')) - self.squashMigrationsAct.setWhatsThis(self.tr( - """<b>Squash Migrations</b>""" - """<p>This squashes migrations of an application of the""" - """ Django project.</p>""" - )) + self.tr("Squash Migrations"), + self.tr("S&quash Migrations"), + 0, + 0, + self, + "django_migration_squash", + ) + self.squashMigrationsAct.setStatusTip( + self.tr("Squash migrations of an application of the project") + ) + self.squashMigrationsAct.setWhatsThis( + self.tr( + """<b>Squash Migrations</b>""" + """<p>This squashes migrations of an application of the""" + """ Django project.</p>""" + ) + ) self.squashMigrationsAct.triggered.connect(self.__squashMigrations) self.actions.append(self.squashMigrationsAct) - + def initMenu(self): """ Public method to initialize the Django menu. - + @return the menu generated @rtype QMenu """ - self.__menus = {} # clear menus references - - menu = QMenu(self.tr('D&jango'), self.__ui) + self.__menus = {} # clear menus references + + menu = QMenu(self.tr("D&jango"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.selectSiteAct) menu.addSeparator() menu.addAction(self.runServerAct) @@ -794,21 +966,21 @@ menu.addAction(self.aboutDjangoAct) menu.addSeparator() menu.addAction(self.helpAct) - + self.__menus["main"] = menu - + return menu def __initDatabaseMenu(self): """ Private method to initialize the database menu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("&Database"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.selectDatabaseNameAct) menu.addSeparator() menu.addAction(self.inspectDatabaseAct) @@ -818,41 +990,41 @@ menu.addAction(self.databaseClientAct) menu.addSeparator() menu.addMenu(self.__initDatabaseSqlMenu()) - + self.__menus["database"] = menu - + return menu - + def __initDatabaseSqlMenu(self): """ Private method to initialize the database SQL submenu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("Show &SQL"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.databaseSqlFlushAct) menu.addAction(self.databaseSqlResetSeqAct) menu.addSeparator() menu.addAction(self.databaseSqlMigrateAct) menu.addAction(self.databaseSqlMigrateBackwardsAct) - + self.__menus["sql"] = menu - + return menu - + def __initMigrationsMenu(self): """ Private method to initialize the Migrations submenu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("&Migrations"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.showMigrationsAct) menu.addAction(self.showMigrationsPlanAct) menu.addSeparator() @@ -863,89 +1035,89 @@ menu.addAction(self.makeMigrationsAct) menu.addSeparator() menu.addAction(self.squashMigrationsAct) - + self.__menus["migrations"] = menu - + return menu - + def __initToolsMenu(self): """ Private method to initialize the tools menu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("&Tools"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.diffSettingsAct) menu.addSeparator() menu.addAction(self.runPythonShellAct) menu.addSeparator() menu.addAction(self.testEmailAct) - + self.__menus["tools"] = menu - + return menu - + def __initTestingMenu(self): """ Private method to initialize the testing menu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("T&esting"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.dumpDataAct) menu.addAction(self.loadDataAct) menu.addSeparator() menu.addAction(self.runTestAct) menu.addAction(self.runDeprecationTestAct) menu.addAction(self.runTestServerAct) - + self.__menus["testing"] = menu - + return menu - + def __initAuthorizationMenu(self): """ Private method to initialize the authorization menu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("&Authorization"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.changePasswordAct) menu.addAction(self.createSuperUserAct) - + self.__menus["authorization"] = menu - + return menu - + def __initSessionMenu(self): """ Private method to initialize the authorization menu. - + @return the menu generated @rtype QMenu """ menu = QMenu(self.tr("&Session"), self.__ui) menu.setTearOffEnabled(True) - + menu.addAction(self.clearSessionsAct) - + self.__menus["session"] = menu - + return menu - + def getMenu(self, name): """ Public method to get a reference to the requested menu. - + @param name name of the menu @type str @return reference to the menu or None, if no menu with the given @@ -956,11 +1128,11 @@ return self.__menus[name] else: return None - + def getMenuNames(self): """ Public method to get the names of all menus. - + @return menu names @rtype list of str """ @@ -969,7 +1141,7 @@ ################################################################## ## methods below implement the various hook related functions ################################################################## - + def registerOpenHook(self): """ Public method to register the open hook to open a translations file @@ -981,55 +1153,60 @@ self.__translationsBrowser.addHookMethodAndMenuEntry( "open", self.openPOEditor, - self.tr("Open with {0}").format( - os.path.basename(editor))) + self.tr("Open with {0}").format(os.path.basename(editor)), + ) else: self.__translationsBrowser.removeHookMethod("open") - + def projectOpenedHooks(self): """ Public method to add our hook methods. """ if self.__ericProject.getProjectType() == "Django": self.__formsBrowser = ( - ericApp().getObject("ProjectBrowser") - .getProjectBrowser("forms") + ericApp().getObject("ProjectBrowser").getProjectBrowser("forms") ) self.__formsBrowser.addHookMethodAndMenuEntry( - "newForm", - self.newForm, self.tr("New template...")) - + "newForm", self.newForm, self.tr("New template...") + ) + self.__ericProject.projectLanguageAddedByCode.connect( - self.__projectLanguageAdded) + self.__projectLanguageAdded + ) self.__translationsBrowser = ( - ericApp().getObject("ProjectBrowser") - .getProjectBrowser("translations")) + ericApp().getObject("ProjectBrowser").getProjectBrowser("translations") + ) self.__translationsBrowser.addHookMethodAndMenuEntry( - "generateAll", - self.updateCatalogs, self.tr("Update all catalogs")) + "generateAll", self.updateCatalogs, self.tr("Update all catalogs") + ) self.__translationsBrowser.addHookMethodAndMenuEntry( "generateSelected", self.updateSelectedCatalogs, - self.tr("Update selected catalogs")) + self.tr("Update selected catalogs"), + ) self.__translationsBrowser.addHookMethodAndMenuEntry( - "generateAllWithObsolete", self.updateCatalogsWithObsolete, - self.tr("Update all catalogs (with obsolete)")) + "generateAllWithObsolete", + self.updateCatalogsWithObsolete, + self.tr("Update all catalogs (with obsolete)"), + ) self.__translationsBrowser.addHookMethodAndMenuEntry( "generateSelectedWithObsolete", self.updateSelectedCatalogsWithObsolete, - self.tr("Update selected catalogs (with obsolete)")) + self.tr("Update selected catalogs (with obsolete)"), + ) self.__translationsBrowser.addHookMethodAndMenuEntry( - "releaseAll", - self.compileCatalogs, self.tr("Compile all catalogs")) + "releaseAll", self.compileCatalogs, self.tr("Compile all catalogs") + ) self.__translationsBrowser.addHookMethodAndMenuEntry( "releaseSelected", self.compileSelectedCatalogs, - self.tr("Compile selected catalogs")) - + self.tr("Compile selected catalogs"), + ) + self.__hooksInstalled = True - + self.registerOpenHook() - + def projectClosedHooks(self): """ Public method to remove our hook methods. @@ -1037,30 +1214,25 @@ if self.__hooksInstalled: self.__formsBrowser.removeHookMethod("newForm") self.__formsBrowser = None - + self.__ericProject.projectLanguageAddedByCode.disconnect( - self.__projectLanguageAdded) - self.__translationsBrowser.removeHookMethod( - "generateAll") - self.__translationsBrowser.removeHookMethod( - "generateSelected") - self.__translationsBrowser.removeHookMethod( - "generateAllWithObsolete") - self.__translationsBrowser.removeHookMethod( - "generateSelectedWithObsolete") - self.__translationsBrowser.removeHookMethod( - "releaseAll") - self.__translationsBrowser.removeHookMethod( - "releaseSelected") + self.__projectLanguageAdded + ) + self.__translationsBrowser.removeHookMethod("generateAll") + self.__translationsBrowser.removeHookMethod("generateSelected") + self.__translationsBrowser.removeHookMethod("generateAllWithObsolete") + self.__translationsBrowser.removeHookMethod("generateSelectedWithObsolete") + self.__translationsBrowser.removeHookMethod("releaseAll") + self.__translationsBrowser.removeHookMethod("releaseSelected") self.__translationsBrowser.removeHookMethod("open") self.__translationsBrowser = None - + self.__hooksInstalled = False - + def newForm(self, path): """ Public method to create a new form. - + @param path full directory path for the new form file @type str """ @@ -1070,66 +1242,72 @@ path, filter, None, - EricFileDialog.DontConfirmOverwrite) - + EricFileDialog.DontConfirmOverwrite, + ) + if not fname: # user aborted or didn't enter a filename return - + ext = QFileInfo(fname).suffix() if not ext: ex = selectedFilter.split("(*")[1].split(")")[0] if ex: fname += ex - + if os.path.exists(fname): res = EricMessageBox.yesNo( self.__ui, self.tr("New Form"), self.tr("The file already exists! Overwrite it?"), - icon=EricMessageBox.Warning) - + icon=EricMessageBox.Warning, + ) + if not res: # user selected to not overwrite return - + try: with open(fname, "w") as f: - f.write('<!DOCTYPE html>') - f.write('<html>\n') - f.write(' <head>\n') + f.write("<!DOCTYPE html>") + f.write("<html>\n") + f.write(" <head>\n") f.write(' <meta content="" />\n') - f.write(' <title></title>\n') - f.write(' <link rel="stylesheet" type="text/css"' - ' href="style.css"/>') - f.write(' <!--[if lte IE 7]>') - f.write(' <link rel="stylesheet" type="text/css"' - ' href="ie.css"/>') - f.write(' <![endif]-->') - f.write(' </head>\n') - f.write('\n') + f.write(" <title></title>\n") + f.write( + ' <link rel="stylesheet" type="text/css"' ' href="style.css"/>' + ) + f.write(" <!--[if lte IE 7]>") + f.write( + ' <link rel="stylesheet" type="text/css"' ' href="ie.css"/>' + ) + f.write(" <![endif]-->") + f.write(" </head>\n") + f.write("\n") f.write(' <body class="bodyclass">\n') f.write(' <div id="container">') - f.write(' </div>') - f.write(' </body>\n') + f.write(" </div>") + f.write(" </body>\n") f.close() - f.write('</html>\n') + f.write("</html>\n") except OSError as e: EricMessageBox.critical( self.__ui, self.tr("New Form"), - self.tr("<p>The new form file <b>{0}</b> could not be" - " created.<br> Problem: {1}</p>") - .format(fname, str(e))) + self.tr( + "<p>The new form file <b>{0}</b> could not be" + " created.<br> Problem: {1}</p>" + ).format(fname, str(e)), + ) return - + self.__ericProject.appendFile(fname) self.__formsBrowser.sourceFile.emit(fname) ################################################################## ## slots below implement general functionality ################################################################## - + def projectClosed(self): """ Public method to handle the closing of a project. @@ -1137,12 +1315,12 @@ if self.__serverProc is not None: self.__serverProcFinished() self.__setCurrentSite(None) - + def __getExecutablePaths(self, file): """ Private method to build all full paths of an executable file from the environment. - + @param file filename of the executable @type str @return list of full executable names, if the executable file is @@ -1151,19 +1329,19 @@ @rtype list of str """ paths = [] - + if os.path.isabs(file): if os.access(file, os.X_OK): return [file] else: return [] - + cur_path = os.path.join(os.curdir, file) if os.path.exists(cur_path) and os.access(cur_path, os.X_OK): paths.append(cur_path) - path = os.getenv('PATH') - + path = os.getenv("PATH") + # environment variable not defined if path is not None: dirs = path.split(os.pathsep) @@ -1171,18 +1349,18 @@ exe = os.path.join(directory, file) if os.access(exe, os.X_OK) and exe not in paths: paths.append(exe) - + return paths - + def supportedPythonVariants(self): """ Public method to get the supported Python variants. - + @return list of supported Python variants @rtype list of str """ variants = [] - for variant in ['Python3']: + for variant in ["Python3"]: virtEnv = self.__getVirtualEnvironment(variant) if virtEnv: if self.__getDjangoAdminCommand(variant): @@ -1200,21 +1378,21 @@ fullCmds = self.__getExecutablePaths(cmd) for fullCmd in fullCmds: try: - with open(fullCmd, 'r', encoding='utf-8') as f: + with open(fullCmd, "r", encoding="utf-8") as f: l0 = f.readline() except OSError: l0 = "" if self.__isSuitableForVariant(variant, l0): variants.append(variant) break - + return variants - + def __isSuitableForVariant(self, variant, line0): """ Private method to test, if a detected command file is suitable for the given Python variant. - + @param variant Python variant to test for @type str @param line0 first line of the executable @@ -1223,16 +1401,15 @@ @rtype bool """ l0 = line0.lower() - ok = (variant.lower() in l0 or - "{0}.".format(variant[-1]) in l0) + ok = variant.lower() in l0 or "{0}.".format(variant[-1]) in l0 ok |= "pypy3" in l0 - + return ok - + def __getVirtualEnvironment(self, language=""): """ Private method to get the path of the virtual environment. - + @param language Python variant to get the virtual environment for (one of '' or 'Python3') @type str @@ -1243,16 +1420,15 @@ language = self.__ericProject.getProjectLanguage() venvName = ( self.__plugin.getPreferences("VirtualEnvironmentNamePy3") - if language == "Python3" else - "" + if language == "Python3" + else "" ) if venvName: - virtEnv = self.__virtualEnvManager.getVirtualenvDirectory( - venvName) + virtEnv = self.__virtualEnvManager.getVirtualenvDirectory(venvName) if not virtEnv: virtEnv = os.path.dirname( - self.__virtualEnvManager.getVirtualenvInterpreter( - venvName)) + self.__virtualEnvManager.getVirtualenvInterpreter(venvName) + ) if virtEnv.endswith(("Scripts", "bin")): virtEnv = os.path.dirname(virtEnv) else: @@ -1264,7 +1440,7 @@ def __getDebugEnvironment(self, language=""): """ Private method to get the path of the debugger environment. - + @param language Python variant to get the debugger environment for (one of '' or 'Python3') @type str @@ -1279,10 +1455,9 @@ venvName = Preferences.getDebugger("Python3VirtualEnv") else: venvName = "" - + if venvName: - debugEnv = self.__virtualEnvManager.getVirtualenvDirectory( - venvName) + debugEnv = self.__virtualEnvManager.getVirtualenvDirectory(venvName) else: debugEnv = "" return debugEnv @@ -1290,7 +1465,7 @@ def __getDjangoAdminCommand(self, language=""): """ Private method to build a django-admin.py command. - + @param language Python variant to get the django-admin.py command for (one of '' or 'Python3') @type str @@ -1299,7 +1474,7 @@ """ if not language: language = self.__ericProject.getProjectLanguage() - + virtualEnv = self.__getVirtualEnvironment(language) if virtualEnv: if isWindowsPlatform(): @@ -1318,8 +1493,7 @@ os.path.join(virtualEnv, "bin", "django-admin"), os.path.join(virtualEnv, "bin", "django-admin.py"), os.path.join(virtualEnv, "local", "bin", "django-admin"), - os.path.join(virtualEnv, "local", "bin", - "django-admin.py"), + os.path.join(virtualEnv, "local", "bin", "django-admin.py"), ] for cmd in cmds: if os.path.exists(cmd): @@ -1341,14 +1515,15 @@ cmd = "" else: if language == "Python3": - cmds = ["django-admin3", - "django-admin3.py", - "django-admin.py-3.10", - "django-admin.py-3.9", - "django-admin.py-3.8", - "django-admin.py-3.7", - "django-admin.py-3.6", - ] + cmds = [ + "django-admin3", + "django-admin3.py", + "django-admin.py-3.10", + "django-admin.py-3.9", + "django-admin.py-3.8", + "django-admin.py-3.7", + "django-admin.py-3.6", + ] else: cmds = [] cmds.extend(["django-admin", "django-admin.py"]) @@ -1357,20 +1532,19 @@ break else: cmd = "" - + return cmd - + def __getPythonExecutable(self): """ Private method to build the Python command. - + @return python command @rtype str """ language = self.__ericProject.getProjectLanguage() if language == "Python3": - venvName = self.__plugin.getPreferences( - "VirtualEnvironmentNamePy3") + venvName = self.__plugin.getPreferences("VirtualEnvironmentNamePy3") if not venvName: # if none configured, use the global one venvName = Preferences.getDebugger("Python3VirtualEnv") @@ -1378,19 +1552,19 @@ venvName = "" python = ( self.__virtualEnvManager.getVirtualenvInterpreter(venvName) - if venvName else - "" + if venvName + else "" ) - + return python - + def __djangoInfo(self): """ Private slot to show some info about Django. """ version = self.getDjangoVersionString() url = "https://www.djangoproject.com" - + msgBox = EricMessageBox.EricMessageBox( EricMessageBox.Question, self.tr("About Django"), @@ -1400,50 +1574,54 @@ " design.</p>" "<p><table>" "<tr><td>Version:</td><td>{0}</td></tr>" - "<tr><td>URL:</td><td><a href=\"{1}\">" + '<tr><td>URL:</td><td><a href="{1}">' "{1}</a></td></tr>" "</table></p>" ).format(version, url), modal=True, - buttons=EricMessageBox.Ok) - msgBox.setIconPixmap(UI.PixmapCache.getPixmap( - os.path.join("ProjectDjango", "icons", - "django64-{0}".format(self.__iconSuffix)))) + buttons=EricMessageBox.Ok, + ) + msgBox.setIconPixmap( + UI.PixmapCache.getPixmap( + os.path.join( + "ProjectDjango", "icons", "django64-{0}".format(self.__iconSuffix) + ) + ) + ) msgBox.exec() - + def getDjangoVersionString(self): """ Public method to get the Django version as a string. - + @return Django version @rtype str """ djangoVersion = "" - - args = ['--version'] + + args = ["--version"] ioEncoding = Preferences.getSystem("IOEncoding") cmd = self.__getDjangoAdminCommand() if cmd: if isWindowsPlatform(): args.insert(0, cmd) cmd = self.__getPythonExecutable() - + process = QProcess() process.start(cmd, args) procStarted = process.waitForStarted() if procStarted: finished = process.waitForFinished(30000) if finished and process.exitCode() == 0: - output = str(process.readAllStandardOutput(), ioEncoding, - 'replace') + output = str(process.readAllStandardOutput(), ioEncoding, "replace") djangoVersion = output.splitlines()[0].strip() - + return djangoVersion - + def getDjangoVersion(self): """ Public method to get the Django version as a tuple. - + @return Django version @rtype tuple of int """ @@ -1455,13 +1633,13 @@ djangoVersionList.append(int(part)) except ValueError: djangoVersionList.append(part) - + return tuple(djangoVersionList) - + def __getApplications(self): """ Private method to ask the user for a list of application names. - + @return list of application names @rtype list of str """ @@ -1470,7 +1648,9 @@ self.tr("Select Applications"), self.tr("Enter the list of applications separated by spaces."), self.getRecentApplications(), - 0, True) + 0, + True, + ) if ok and applStr != "": self.setMostRecentApplication(applStr) return applStr.split() @@ -1487,41 +1667,41 @@ if ra is not None: maxRecentApps = self.__plugin.getPreferences("RecentNumberApps") self.__recentApplications = ra[:maxRecentApps] - + def __saveRecentApplications(self): """ Private method to save the list of recently used applications list. """ - Preferences.Prefs.rsettings.setValue(self.RecentApplicationsKey, - self.__recentApplications) + Preferences.Prefs.rsettings.setValue( + self.RecentApplicationsKey, self.__recentApplications + ) Preferences.Prefs.rsettings.sync() - + def getRecentApplications(self): """ Public method to get the list of recent applications. - + @return list of recent applications entries (list of strings) """ self.__loadRecentApplications() return self.__recentApplications - + def setMostRecentApplication(self, applStr): """ Public method to set the most recently used applications entry. - + @param applStr applications entry @type str """ if applStr in self.__recentApplications: self.__recentApplications.remove(applStr) self.__recentApplications.insert(0, applStr) - + maxRecentApps = self.__plugin.getPreferences("RecentNumberApps") if len(self.__recentApplications) > maxRecentApps: - self.__recentApplications = ( - self.__recentApplications[:maxRecentApps]) + self.__recentApplications = self.__recentApplications[:maxRecentApps] self.__saveRecentApplications() - + def __loadRecentTestData(self): """ Private method to load the recently used test data lists. @@ -1532,26 +1712,26 @@ "RecentTestExcludeTags": [], } Preferences.Prefs.rsettings.sync() - maxRecentTestData = self.__plugin.getPreferences( - "RecentNumberTestData") + maxRecentTestData = self.__plugin.getPreferences("RecentNumberTestData") for key in self.__recentTestData: recent = Preferences.Prefs.rsettings.value("Django/" + key) if recent is not None: self.__recentTestData[key] = recent[:maxRecentTestData] - + def __saveRecentTestData(self): """ Private method to save the list of recently used test data. """ for key in self.__recentTestData: - Preferences.Prefs.rsettings.setValue("Django/" + key, - self.__recentTestData[key]) + Preferences.Prefs.rsettings.setValue( + "Django/" + key, self.__recentTestData[key] + ) Preferences.Prefs.rsettings.sync() - + def getRecentTestData(self, key): """ Public method to get the list of recent test data. - + @param key key (name) of the test data to get @type str @return list of recent test data entries @@ -1559,11 +1739,11 @@ """ self.__loadRecentTestData() return self.__recentTestData[key] - + def setMostRecentTestData(self, key, data): """ Public method to set the most recently used test data entry. - + @param key key (name) of the test data to set @type str @param data test data entry to be set @@ -1572,50 +1752,49 @@ if data in self.__recentTestData[key]: self.__recentTestData[key].remove(data) self.__recentTestData[key].insert(0, data) - - maxRecentTestData = self.__plugin.getPreferences( - "RecentNumberTestData") + + maxRecentTestData = self.__plugin.getPreferences("RecentNumberTestData") if len(self.__recentTestData[key]) > maxRecentTestData: - self.__recentTestData[key] = ( - self.__recentTestData[key][:maxRecentTestData]) + self.__recentTestData[key] = self.__recentTestData[key][:maxRecentTestData] self.__saveRecentTestData() - + def getProjectPath(self): """ Public method to get the path of the eric7 project. - + @return path of the eric7 project @rtype str """ return self.__ericProject.getProjectPath() - + def __showHelpIndex(self): """ Private slot to show the help index page. """ - page = os.path.join(os.path.dirname(__file__), - "Documentation", "help", "index.html") + page = os.path.join( + os.path.dirname(__file__), "Documentation", "help", "index.html" + ) self.__ui.launchHelpViewer(page) - + def __isSpawningConsole(self, consoleCmd): """ Private method to check, if the given console is a spawning console. - + @param consoleCmd console command @type str @return tuple of two entries giving an indication, if the console is spawning and the (possibly) cleaned console command @rtype tuple of (bool, str) """ - if consoleCmd and consoleCmd[0] == '@': + if consoleCmd and consoleCmd[0] == "@": return (True, consoleCmd[1:]) else: return (False, consoleCmd) - + def __adjustWorkingDirectory(self, args, wd): """ Private method to adjust the working directory in the arguments list. - + @param args list of arguments to be modified @type list of str @param wd working directory @@ -1629,24 +1808,24 @@ if args[index].startswith("--working-directory="): args[index] = "--working-directory={0}".format(wd) break - + ################################################################## ## slots below implement creation functions ################################################################## - + def newProjectCreated(self): """ Public slot to finish up the newly generated project. """ if self.__ericProject.getProjectType() == "Django": ppath = self.__ericProject.getProjectPath() - + # get rid of an __init__.py file because it would be in our way initModule = os.path.join(ppath, "__init__.py") if os.path.exists(initModule): self.__ericProject.deleteFile("__init__.py") self.__ericProject.saveProject() - + def startProjectOrApplication(self): """ Public slot to start a new Django project or application. @@ -1658,25 +1837,29 @@ selection, ok = QInputDialog.getItem( self.__ui, self.tr("Start Django"), - self.tr("Select if this project should be a " - "Django Project or Application.<br />" - "Select the empty entry for none."), + self.tr( + "Select if this project should be a " + "Django Project or Application.<br />" + "Select the empty entry for none." + ), selections, - 0, False) + 0, + False, + ) if ok and bool(selection): if selection == projectStr: path, projectName = os.path.split( - self.__ericProject.getProjectPath()) + self.__ericProject.getProjectPath() + ) self.__createProject(projectName, path) elif selection == applStr: - path, applName = os.path.split( - self.__ericProject.getProjectPath()) + path, applName = os.path.split(self.__ericProject.getProjectPath()) self.__createApplication(applName, path) - + def __createProject(self, projectName, path): """ Private slot to create a new Django project. - + @param projectName name of the new project @type str @param path the directory where the project should be created @@ -1685,26 +1868,32 @@ @rtype bool """ title = self.tr("Start Django Project") - + # remove the project directory if it exists already ppath = os.path.join(path, projectName) if os.path.exists(ppath): okToRemove = EricMessageBox.yesNo( self.__ui, title, - self.tr("""<p>The Django project path <b>{0}</b> exists""" - """ already. Shall it be removed and recreated?""" - """</p>""").format(ppath)) + self.tr( + """<p>The Django project path <b>{0}</b> exists""" + """ already. Shall it be removed and recreated?""" + """</p>""" + ).format(ppath), + ) if not okToRemove: EricMessageBox.information( self.__ui, title, - self.tr("""<p>Please add the files to the eric project""" - """ manually.</p>""")) + self.tr( + """<p>Please add the files to the eric project""" + """ manually.</p>""" + ), + ) return True - + shutil.rmtree(ppath, ignore_errors=True) - + args = [] cmd = self.__getDjangoAdminCommand() if cmd: @@ -1715,35 +1904,35 @@ EricMessageBox.critical( self.__ui, title, - self.tr("""<p>The <b>django-admin.py</b> script is""" - """ not in the path. Aborting...</p>""")) + self.tr( + """<p>The <b>django-admin.py</b> script is""" + """ not in the path. Aborting...</p>""" + ), + ) return False - + args.append("startproject") args.append(projectName) - + dia = DjangoDialog( - title, - msgSuccess=self.tr("Django project created successfully.")) + title, msgSuccess=self.tr("Django project created successfully.") + ) res = dia.startProcess(args, path) if res: dia.exec() - + # create the base directory for translations i18nPath = os.path.join(path, projectName, "locale") if not os.path.exists(i18nPath): os.makedirs(i18nPath) - - if ( - os.path.join(path, projectName) == - self.__ericProject.getProjectPath() - ): + + if os.path.join(path, projectName) == self.__ericProject.getProjectPath(): self.__setCurrentSite("") else: self.__setCurrentSite(projectName) - + return res - + def __startProject(self): """ Private slot to start a new Django project. @@ -1752,23 +1941,24 @@ self.__ui, self.tr("Start Django Project"), self.tr("Enter the name of the new Django project."), - QLineEdit.EchoMode.Normal) + QLineEdit.EchoMode.Normal, + ) if ok and projectName != "": - res = self.__createProject(projectName, - self.__ericProject.getProjectPath()) + res = self.__createProject(projectName, self.__ericProject.getProjectPath()) if res: # search for new files and add them to the project - sitePath = os.path.join(self.__ericProject.getProjectPath(), - projectName) + sitePath = os.path.join( + self.__ericProject.getProjectPath(), projectName + ) for entry in os.walk(sitePath): for fileName in entry[2]: fullName = os.path.join(entry[0], fileName) self.__ericProject.appendFile(fullName) - + def __createApplication(self, applName, path, isGlobal=True): """ Private slot to create a new Django application. - + @param applName name of the new application @type str @param path the directory where the application should be created @@ -1779,12 +1969,12 @@ @rtype bool """ title = self.tr("Start Django Application") - + # remove the application directory if it exists already apath = os.path.join(path, applName) if os.path.exists(apath): shutil.rmtree(apath, ignore_errors=True) - + args = [] if isGlobal: cmd = self.__getDjangoAdminCommand() @@ -1796,28 +1986,31 @@ EricMessageBox.critical( self.__ui, title, - self.tr("""<p>The <b>django-admin.py</b> script""" - """ is not in the path.""" - """ Aborting...</p>""")) + self.tr( + """<p>The <b>django-admin.py</b> script""" + """ is not in the path.""" + """ Aborting...</p>""" + ), + ) return False else: args.append(self.__getPythonExecutable()) args.append("manage.py") try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return False args.append("startapp") args.append(applName) - + dia = DjangoDialog( - title, - msgSuccess=self.tr("Django application created successfully.")) + title, msgSuccess=self.tr("Django application created successfully.") + ) res = dia.startProcess(args, path) if res: dia.exec() return res - + def __startGlobalApplication(self): """ Private slot to start a new global Django application. @@ -1825,21 +2018,21 @@ applName, ok = QInputDialog.getText( self.__ui, self.tr("Start Global Django Application"), - self.tr("Enter the name of the new global Django" - " application."), - QLineEdit.EchoMode.Normal) + self.tr("Enter the name of the new global Django" " application."), + QLineEdit.EchoMode.Normal, + ) if ok and applName != "": - res = self.__createApplication(applName, - self.__ericProject.getProjectPath()) + res = self.__createApplication( + applName, self.__ericProject.getProjectPath() + ) if res: # search for new files and add them to the project - appPath = os.path.join(self.__ericProject.getProjectPath(), - applName) + appPath = os.path.join(self.__ericProject.getProjectPath(), applName) for entry in os.walk(appPath): for fileName in entry[2]: fullName = os.path.join(entry[0], fileName) self.__ericProject.appendFile(fullName) - + def __startLocalApplication(self): """ Private slot to start a new local Django application. @@ -1848,7 +2041,8 @@ self.__ui, self.tr("Start Local Django Application"), self.tr("Enter the name of the new local Django application."), - QLineEdit.EchoMode.Normal) + QLineEdit.EchoMode.Normal, + ) if ok and applName != "": res = self.__createApplication(applName, "", False) if res: @@ -1859,17 +2053,17 @@ for fileName in entry[2]: fullName = os.path.join(entry[0], fileName) self.__ericProject.appendFile(fullName) - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + ################################################################## ## methods below implement site related functions ################################################################## - + def __findSites(self): """ Private method to determine the relative path to all manage.py scripts. - + @return list of sites @rtype list of str """ @@ -1878,7 +2072,7 @@ if os.path.basename(file) == "manage.py": sites.append(os.path.dirname(file)) return sites - + def __selectSite(self): """ Private method to select a site to work with. @@ -1899,33 +2093,34 @@ self.tr("Select Project"), self.tr("Select the Django project to work with."), sites, - cur, False) + cur, + False, + ) if not ok: site = None self.__setCurrentSite(site) - + def __sitePath(self): """ Private method to calculate the full path of the Django site. - + @return path of the site @rtype str - @exception DjangoNoSiteSelectedException raised, if no site is selected + @exception DjangoNoSiteSelectedError raised, if no site is selected """ if self.__currentSite is None: self.__selectSite() - + if self.__currentSite is None: - raise DjangoNoSiteSelectedException + raise DjangoNoSiteSelectedError else: - path = os.path.join(self.__ericProject.getProjectPath(), - self.__currentSite) + path = os.path.join(self.__ericProject.getProjectPath(), self.__currentSite) return path - + def __setCurrentSite(self, site): """ Private slot to set the current site. - + @param site name of the site @type str """ @@ -1937,42 +2132,43 @@ else: curSite = self.__currentSite self.selectSiteAct.setText( - self.tr('&Current Django project ({0})').format(curSite)) - + self.tr("&Current Django project ({0})").format(curSite) + ) + if self.__currentSite is None: self.__ericProject.setTranslationPattern("") else: self.__ericProject.setTranslationPattern( - os.path.join(site, "locale", "%language%", "LC_MESSAGES", - "django.po") + os.path.join(site, "locale", "%language%", "LC_MESSAGES", "django.po") ) - + def __site(self): """ Private method to get the name of the current site. - + @return name of the site @rtype str - @exception DjangoNoSiteSelectedException raised, if no site is selected + @exception DjangoNoSiteSelectedError raised, if no site is selected """ if self.__currentSite is None: self.__selectSite() - + if self.__currentSite is None: - raise DjangoNoSiteSelectedException + raise DjangoNoSiteSelectedError else: return self.__currentSite ################################################################## ## slots below implement run functions ################################################################## - + def __runServer(self): """ Private slot to start the Django Web server. """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommand"))[1] + self.__plugin.getPreferences("ConsoleCommand") + )[1] if consoleCmd: args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) @@ -1986,40 +2182,41 @@ addr = self.__plugin.getPreferences("ServerAddress") if addr: args.append(addr) - - with contextlib.suppress(DjangoNoSiteSelectedException): + + with contextlib.suppress(DjangoNoSiteSelectedError): if Utilities.isWindowsPlatform(): serverProcStarted, pid = QProcess.startDetached( - args[0], args[1:], self.__sitePath()) + args[0], args[1:], self.__sitePath() + ) else: if self.__serverProc is not None: self.__serverProcFinished() - + self.__serverProc = QProcess() - self.__serverProc.finished.connect( - self.__serverProcFinished) + self.__serverProc.finished.connect(self.__serverProcFinished) self.__serverProc.setWorkingDirectory(self.__sitePath()) self.__serverProc.start(args[0], args[1:]) serverProcStarted = self.__serverProc.waitForStarted() if not serverProcStarted: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django server could not be started.')) - + self.tr("Process Generation Error"), + self.tr("The Django server could not be started."), + ) + def __serverProcFinished(self): """ Private slot connected to the finished signal. """ if ( - self.__serverProc is not None and - self.__serverProc.state() != QProcess.ProcessState.NotRunning + self.__serverProc is not None + and self.__serverProc.state() != QProcess.ProcessState.NotRunning ): self.__serverProc.terminate() QTimer.singleShot(2000, self.__serverProc.kill) self.__serverProc.waitForFinished(3000) self.__serverProc = None - + def __runBrowser(self): """ Private slot to start the default web browser with the server URL. @@ -2028,10 +2225,10 @@ ipv6 = self.__plugin.getPreferences("UseIPv6") if addr: # test for an IPv6 and port address - if ']:' in addr: - addr, port = addr.rsplit(':', 1) - elif ':' in addr: - addr, port = addr.split(':', 1) + if "]:" in addr: + addr, port = addr.rsplit(":", 1) + elif ":" in addr: + addr, port = addr.split(":", 1) else: port = addr if ipv6: @@ -2050,9 +2247,11 @@ if not res: EricMessageBox.critical( None, - self.tr('Run Web-Browser'), - self.tr('Could not start the web-browser for the' - ' url "{0}".').format(url.toString())) + self.tr("Run Web-Browser"), + self.tr( + "Could not start the web-browser for the" ' url "{0}".' + ).format(url.toString()), + ) else: self.__ui.launchHelpViewer(url) @@ -2060,7 +2259,7 @@ ## slots below implement functions to save and load recently used ## database names ################################################################## - + def __loadRecentDatabaseNames(self): """ Private method to load the list of recently used database names. @@ -2069,46 +2268,50 @@ Preferences.Prefs.rsettings.sync() rdb = Preferences.Prefs.rsettings.value(self.RecentDatabaseNamesKey) if rdb is not None: - maxRecentDatabaseNames = ( - self.__plugin.getPreferences("RecentNumberDatabaseNames")) + maxRecentDatabaseNames = self.__plugin.getPreferences( + "RecentNumberDatabaseNames" + ) self.__recentDatabaseNames = rdb[:maxRecentDatabaseNames] - + def __saveRecentDatabaseNames(self): """ Private method to save the list of recently used database names. """ - Preferences.Prefs.rsettings.setValue(self.RecentDatabaseNamesKey, - self.__recentDatabaseNames) + Preferences.Prefs.rsettings.setValue( + self.RecentDatabaseNamesKey, self.__recentDatabaseNames + ) Preferences.Prefs.rsettings.sync() - + def getRecentDatabaseNames(self): """ Public method to get the list of recently used database names. - + @return list of recently used database names @rtype list of str """ self.__loadRecentDatabaseNames() return self.__recentDatabaseNames - + def setMostRecentDatabaseNames(self, dbName): """ Public method to set the most recently used database names. - + @param dbName database name @type str """ if dbName in self.__recentDatabaseNames: self.__recentDatabaseNames.remove(dbName) self.__recentDatabaseNames.insert(0, dbName) - - maxRecentDatabaseNames = ( - self.__plugin.getPreferences("RecentNumberDatabaseNames")) + + maxRecentDatabaseNames = self.__plugin.getPreferences( + "RecentNumberDatabaseNames" + ) if len(self.__recentDatabaseNames) > maxRecentDatabaseNames: - self.__recentDatabaseNames = ( - self.__recentDatabaseNames[:maxRecentDatabaseNames]) + self.__recentDatabaseNames = self.__recentDatabaseNames[ + :maxRecentDatabaseNames + ] self.__saveRecentDatabaseNames() - + def __selectDatabaseName(self): """ Private method to select the name of the database to work with. @@ -2116,70 +2319,73 @@ recentDatabases = self.getRecentDatabaseNames()[:] if "" not in recentDatabases: recentDatabases.insert(1, "") - + selectedDatabase, ok = QInputDialog.getItem( self.__ui, self.tr("Database Name"), self.tr("Select a database name (leave empty for default):"), recentDatabases, - 0, True) - + 0, + True, + ) + if ok: self.setMostRecentDatabaseNames(selectedDatabase) self.__setCurrentDatabase(selectedDatabase) - + def __setCurrentDatabase(self, database): """ Private method to set the database name to be used. - + @param database name of the database @type str """ if database is None: database = self.getRecentDatabaseNames()[0] - + self.__currentDatabase = database curDb = database if database else self.tr("<default>") self.selectDatabaseNameAct.setText( - self.tr('&Current Database ({0})').format(curDb)) - + self.tr("&Current Database ({0})").format(curDb) + ) + def currentDatabase(self): """ Public method to get the database name to be used. - + @return database name @rtype str """ return self.__currentDatabase - + ################################################################## ## slots below implement database related functions ################################################################## - + def __databaseInspect(self): """ Private slot to introspect the database and output a Django model module. """ title = self.tr("Introspect Database") - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("inspectdb") if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) - + try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + dia = DjangoDialog(title, fixed=True, linewrap=False) res = dia.startProcess(args, path, False) if res: dia.exec() - + def __databaseFlush(self): """ Private slot to return all database tables to the state just after @@ -2187,16 +2393,18 @@ """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + title = self.tr("Flush Database") - + res = EricMessageBox.yesNo( self.__ui, title, - self.tr("""Flushing the database will destroy all data.""" - """ Are you sure?""")) + self.tr( + """Flushing the database will destroy all data.""" """ Are you sure?""" + ), + ) if res: args = [] args.append(self.__getPythonExecutable()) @@ -2205,21 +2413,21 @@ args.append("--noinput") if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) - + dia = DjangoDialog( - title, - msgSuccess=self.tr("Database tables flushed" - " successfully.")) + title, msgSuccess=self.tr("Database tables flushed" " successfully.") + ) res = dia.startProcess(args, path) if res: dia.exec() - + def __runDatabaseClient(self): """ Private slot to start a database client for a Django project. """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommand"))[1] + self.__plugin.getPreferences("ConsoleCommand") + )[1] if consoleCmd: args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) @@ -2228,24 +2436,25 @@ args.append("dbshell") if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) - with contextlib.suppress(DjangoNoSiteSelectedException): + with contextlib.suppress(DjangoNoSiteSelectedError): wd = self.__sitePath() self.__adjustWorkingDirectory(args, wd) started, pid = QProcess.startDetached(args[0], args[1:], wd) if not started: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django process could not be started.')) - + self.tr("Process Generation Error"), + self.tr("The Django process could not be started."), + ) + ####################################################################### ## slots below implement database functions outputting SQL statements ####################################################################### - + def __sqlCommand(self, title, command, requestApps=True): """ Private method to perform an SQL creation function. - + @param title dialog title @type str @param command Django sql... command @@ -2256,16 +2465,16 @@ """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + if requestApps: apps = self.__getApplications() if not apps: return else: apps = [] - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2273,62 +2482,59 @@ if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) args += apps - + fileFilter = self.tr("SQL Files (*.sql)") - - dia = DjangoDialog(title, fixed=True, linewrap=False, - saveFilters=fileFilter) + + dia = DjangoDialog(title, fixed=True, linewrap=False, saveFilters=fileFilter) res = dia.startProcess(args, path, False) if res: dia.exec() - + def __databaseSqlFlushDatabase(self): """ Private slot to print a list of statements to return all database tables to their initial state. """ self.__sqlCommand(self.tr("Flush Database"), "sqlflush", False) - + def __databaseSqlResetSequences(self): """ Private slot to print the SQL statements for resetting sequences for one or more applications. """ self.__sqlCommand(self.tr("Reset Sequences"), "sqlsequencereset") - + def __databaseSqlMigrate(self, backwards=False): """ Private slot to print the SQL statements for a migration of an application. - + @param backwards flag indicating to generate the SQL code to revert a migration @type bool """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + migrations = self.__getMigrations() if not migrations: EricMessageBox.information( - None, - self.tr("SQL Migrate"), - self.tr("""No migrations available.""")) + None, self.tr("SQL Migrate"), self.tr("""No migrations available.""") + ) return - + title = self.tr("SQL Migrate") - - from .DjangoMigrationSelectionDialog import ( - DjangoMigrationSelectionDialog + + from .DjangoMigrationSelectionDialog import DjangoMigrationSelectionDialog + + dlg = DjangoMigrationSelectionDialog( + migrations, migrationRequired=True, suffix=self.__iconSuffix ) - dlg = DjangoMigrationSelectionDialog(migrations, - migrationRequired=True, - suffix=self.__iconSuffix) if dlg.exec() == QDialog.DialogCode.Accepted: app, migration = dlg.getData() - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2339,57 +2545,64 @@ args.append("--backwards") args.append(app) args.append(migration) - + fileFilter = self.tr("SQL Files (*.sql)") - - dia = DjangoDialog(title, fixed=True, linewrap=False, - saveFilters=fileFilter) + + dia = DjangoDialog( + title, fixed=True, linewrap=False, saveFilters=fileFilter + ) res = dia.startProcess(args, path, False) if res: dia.exec() - + ################################################################## ## slots below implement migration related functions ################################################################## - + def __showMigrationsList(self): """ Private slot to show the available migrations and their status. """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + from .DjangoMigrationsListDialog import DjangoMigrationsListDialog + self.__migrationsListDialog = DjangoMigrationsListDialog( - DjangoMigrationsListDialog.MigrationsListMode, self, self.__ui) + DjangoMigrationsListDialog.MigrationsListMode, self, self.__ui + ) self.__migrationsListDialog.show() - self.__migrationsListDialog.start(self.__getPythonExecutable(), path, - self.__currentDatabase) - + self.__migrationsListDialog.start( + self.__getPythonExecutable(), path, self.__currentDatabase + ) + def __showMigrationsPlan(self): """ Private slot to show the migrations plan. """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + from .DjangoMigrationsListDialog import DjangoMigrationsListDialog + self.__migrationsPlanDialog = DjangoMigrationsListDialog( - DjangoMigrationsListDialog.MigrationsPlanMode, self, self.__ui) + DjangoMigrationsListDialog.MigrationsPlanMode, self, self.__ui + ) self.__migrationsPlanDialog.show() - self.__migrationsPlanDialog.start(self.__getPythonExecutable(), path, - self.__currentDatabase) - + self.__migrationsPlanDialog.start( + self.__getPythonExecutable(), path, self.__currentDatabase + ) + def __applyAllMigrations(self): """ Private slot to apply all migrations. """ self.applyMigrations() - + def __applySelectedMigrations(self): """ Private slot to apply selected migrations of a selected app. @@ -2399,22 +2612,21 @@ EricMessageBox.information( None, self.tr("Apply Selected Migrations"), - self.tr("""No migrations available.""")) + self.tr("""No migrations available."""), + ) return - - from .DjangoMigrationSelectionDialog import ( - DjangoMigrationSelectionDialog - ) - dlg = DjangoMigrationSelectionDialog(migrations, - suffix=self.__iconSuffix) + + from .DjangoMigrationSelectionDialog import DjangoMigrationSelectionDialog + + dlg = DjangoMigrationSelectionDialog(migrations, suffix=self.__iconSuffix) if dlg.exec() == QDialog.DialogCode.Accepted: app, migration = dlg.getData() self.applyMigrations(app=app, migration=migration) - + def applyMigrations(self, app=None, migration=None): """ Public slot to apply migrations. - + @param app name of an application to apply migrations for @type str @param migration name of a migration to update to @@ -2422,15 +2634,15 @@ """ title = ( self.tr("Unapply Migrations") - if migration == "zero" else - self.tr("Apply Migrations") + if migration == "zero" + else self.tr("Apply Migrations") ) - + try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2440,12 +2652,12 @@ args.append(app) if migration: args.append(migration) - + dia = DjangoDialog(title) res = dia.startProcess(args, path) if res: dia.exec() - + def __unapplyMigrations(self): """ Private slot to revert all migrations of an application. @@ -2455,46 +2667,52 @@ EricMessageBox.information( None, self.tr("Unapply Migrations"), - self.tr("""No migrations available.""")) + self.tr("""No migrations available."""), + ) return - + app, ok = QInputDialog.getItem( None, self.tr("Unapply Migrations"), self.tr("Select an application:"), [""] + apps, - 0, False) + 0, + False, + ) if ok and app: self.applyMigrations(app=app, migration="zero") - + def __getMigrations(self): """ Private method to get the available migrations. - + @return dictionary containing the available migrations @rtype dict with app name as key (str) and list of tuples of applied indication (bool) and migration name (str) as value """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return {} - + args = [] args.append("manage.py") args.append("showmigrations") args.append("--list") if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) - + migrations = {} proc = QProcess() if path: proc.setWorkingDirectory(path) proc.start(self.__getPythonExecutable(), args) if proc.waitForStarted() and proc.waitForFinished(): - output = str(proc.readAllStandardOutput(), - Preferences.getSystem("IOEncoding"), 'replace') + output = str( + proc.readAllStandardOutput(), + Preferences.getSystem("IOEncoding"), + "replace", + ) if output: recentApp = "" for line in output.splitlines(): @@ -2510,12 +2728,13 @@ if recentApp: migrations[recentApp].append((applied, name)) return migrations - + def __makeMigrations(self): """ Private slot to generate migrations for the Django project. """ from .DjangoMakeMigrationsDialog import DjangoMakeMigrationsDialog + dlg = DjangoMakeMigrationsDialog(self.getRecentApplications()) if dlg.exec() == QDialog.DialogCode.Accepted: apps, migration, dryRun, empty, merge = dlg.getData() @@ -2523,12 +2742,13 @@ self.setMostRecentApplication(apps) apps = apps.split() self.makeMigrations(apps, migration, dryRun, empty, merge) - - def makeMigrations(self, apps, migration=None, dryRun=False, empty=False, - merge=False): + + def makeMigrations( + self, apps, migration=None, dryRun=False, empty=False, merge=False + ): """ Public method to generate migrations. - + @param apps list of application names to generate migrations for @type list of str @param migration name of the migration to generate @@ -2541,12 +2761,12 @@ @type bool """ title = self.tr("Make Migrations") - + try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2562,12 +2782,12 @@ args.append("--merge") if apps: args += apps - + dia = DjangoDialog(title, showInput=True) res = dia.startProcess(args, path) if res: dia.exec() - + def __squashMigrations(self): """ Private slot to squash migrations. @@ -2577,24 +2797,25 @@ EricMessageBox.information( None, self.tr("Squash Migrations"), - self.tr("""No migrations available.""")) + self.tr("""No migrations available."""), + ) return - + from .DjangoSquashMigrationSelectionDialog import ( - DjangoSquashMigrationSelectionDialog + DjangoSquashMigrationSelectionDialog, ) - dlg = DjangoSquashMigrationSelectionDialog( - migrations, self, self.__iconSuffix) + + dlg = DjangoSquashMigrationSelectionDialog(migrations, self, self.__iconSuffix) if dlg.exec() == QDialog.DialogCode.Accepted: app, start, end, noOptimize, name = dlg.getData() - + title = self.tr("Squash Migrations") - + try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2608,27 +2829,28 @@ if start: args.append(start) args.append(end) - + dia = DjangoDialog(title) res = dia.startProcess(args, path) if res: dia.exec() - + ################################################################## ## slots below implement some tool functions ################################################################## - + def __diffSettings(self): """ Private slot to show the changes made to the settings.py file. """ title = self.tr("Diff Settings") - + from .DjangoDiffsettingsDataDialog import DjangoDiffsettingsDataDialog + dlg = DjangoDiffsettingsDataDialog(self, self.__ui) if dlg.exec() == QDialog.DialogCode.Accepted: showAll, defaultModule, outputFormat = dlg.getData() - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2639,54 +2861,58 @@ args.append("--default={0}".format(defaultModule)) if outputFormat: args.append("--output={0}".format(outputFormat)) - + try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + dia = DjangoDialog(title, fixed=True, linewrap=False) res = dia.startProcess(args, path, False) if res: dia.exec() - + def __runPythonShell(self): """ Private slot to start a Python console for a Django project. """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommand"))[1] + self.__plugin.getPreferences("ConsoleCommand") + )[1] if consoleCmd: args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("shell") - args.append("--interface={0}".format( - self.__plugin.getPreferences("Python3ConsoleType"))) - with contextlib.suppress(DjangoNoSiteSelectedException): + args.append( + "--interface={0}".format( + self.__plugin.getPreferences("Python3ConsoleType") + ) + ) + with contextlib.suppress(DjangoNoSiteSelectedError): wd = self.__sitePath() self.__adjustWorkingDirectory(args, wd) started, pid = QProcess.startDetached(args[0], args[1:], wd) if not started: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django process could not be started.')) - + self.tr("Process Generation Error"), + self.tr("The Django process could not be started."), + ) + def __sendTestEmail(self): """ Private slot to send a test email through Django. """ title = self.tr("Send Test Email") - - from .DjangoSendTestEmailDataDialog import ( - DjangoSendTestEmailDataDialog - ) + + from .DjangoSendTestEmailDataDialog import DjangoSendTestEmailDataDialog + dlg = DjangoSendTestEmailDataDialog(self.__ui) if dlg.exec() == QDialog.DialogCode.Accepted: managers, admins, recipients = dlg.getData() - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2696,71 +2922,72 @@ if admins: args.append("--admins") args.extend(recipients) - + try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + dia = DjangoDialog( title, linewrap=False, msgSuccess=self.tr("Test Email sent successfully."), - msgError=self.tr("Test Email could not be sent.") + msgError=self.tr("Test Email could not be sent."), ) res = dia.startProcess(args, path, False) if res: dia.exec() - + ################################################################## ## slots below implement caching functions ################################################################## - + def __createCacheTables(self): """ Private slot to create the tables for the SQL caching backend. """ title = self.tr("Create Cache Tables") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("createcachetable") if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) - + dia = DjangoDialog( - title, - msgSuccess=self.tr("Cache tables created successfully.")) + title, msgSuccess=self.tr("Cache tables created successfully.") + ) res = dia.startProcess(args, wd) if res: dia.exec() - + ################################################################## ## slots below implement testing functions ################################################################## - + def __dumpData(self): """ Private slot to dump the database data to a fixture. """ title = self.tr("Dump Data") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + from .DjangoDumpdataDataDialog import DjangoDumpdataDataDialog + dlg = DjangoDumpdataDataDialog(self, self.__ui) if dlg.exec() == QDialog.DialogCode.Accepted: appls, excls, dumpFormat, indent = dlg.getData() - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2772,36 +2999,38 @@ if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) args += appls - + if dumpFormat == "json": fileFilters = self.tr("JSON Files (*.json)") elif dumpFormat == "xml": fileFilters = self.tr("XML Files (*.xml)") elif dumpFormat == "yaml": fileFilters = self.tr("YAML Files (*.yaml)") - + dia = DjangoDialog( - title, fixed=True, linewrap=False, saveFilters=fileFilters) + title, fixed=True, linewrap=False, saveFilters=fileFilters + ) res = dia.startProcess(args, wd, showCommand=False) if res: dia.exec() - + def __loadData(self): """ Private slot to load data from fixture files. """ title = self.tr("Load Data") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + from .DjangoLoaddataDataDialog import DjangoLoaddataDataDialog + dlg = DjangoLoaddataDataDialog(self, self.__ui) if dlg.exec() == QDialog.DialogCode.Accepted: fixtures, excludes, appLabel, ignore = dlg.getData() - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -2815,37 +3044,38 @@ if self.__currentDatabase: args.append("--database={0}".format(self.__currentDatabase)) args += fixtures - + dia = DjangoDialog(title) res = dia.startProcess(args, wd) if res: dia.exec() - + def __runTestSuite(self, deprecation=False): """ Private slot to run the test suite for applications or the whole site. - + @param deprecation flag indicating to test for deprecation warnings @type bool """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommandNoClose"))[1] + self.__plugin.getPreferences("ConsoleCommandNoClose") + )[1] if consoleCmd: try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + from .DjangoTestDataDialog import DjangoTestDataDialog + dlg = DjangoTestDataDialog( - self, self.__plugin.getPreferences("KeepTestDatabase"), - self.__ui) + self, self.__plugin.getPreferences("KeepTestDatabase"), self.__ui + ) if dlg.exec() == QDialog.DialogCode.Accepted: - labels, pattern, tags, excludeTags, keep, reverse = ( - dlg.getData()) - + labels, pattern, tags, excludeTags, keep, reverse = dlg.getData() + self.__plugin.setPreferences("KeepTestDatabase", keep) - + args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) args.append(self.__getPythonExecutable()) @@ -2864,30 +3094,31 @@ if reverse: args.append("--reverse") args.extend(labels) - + self.__adjustWorkingDirectory(args, wd) started, pid = QProcess.startDetached(args[0], args[1:], wd) if not started: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django process could not be started.')) - + self.tr("Process Generation Error"), + self.tr("The Django process could not be started."), + ) + def __runTestServer(self): """ Private slot to run a development server with data from a set of fixtures. """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommand"))[1] + self.__plugin.getPreferences("ConsoleCommand") + )[1] if consoleCmd: - from .DjangoRunTestServerDataDialog import ( - DjangoRunTestServerDataDialog - ) + from .DjangoRunTestServerDataDialog import DjangoRunTestServerDataDialog + dlg = DjangoRunTestServerDataDialog(self, self.__ui) if dlg.exec() == QDialog.DialogCode.Accepted: fixtures = dlg.getData() - + args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) args.append(self.__getPythonExecutable()) @@ -2899,59 +3130,61 @@ if addr: args.append("--addrport={0}".format(addr)) args += fixtures - - with contextlib.suppress(DjangoNoSiteSelectedException): + + with contextlib.suppress(DjangoNoSiteSelectedError): if Utilities.isWindowsPlatform(): serverProcStarted, pid = QProcess.startDetached( - args[0], args[1:], self.__sitePath()) + args[0], args[1:], self.__sitePath() + ) else: if self.__testServerProc is not None: self.__testServerProcFinished() - + self.__testServerProc = QProcess() self.__testServerProc.finished.connect( - self.__serverProcFinished) - self.__testServerProc.setWorkingDirectory( - self.__sitePath()) + self.__serverProcFinished + ) + self.__testServerProc.setWorkingDirectory(self.__sitePath()) self.__testServerProc.start(args[0], args[1:]) - serverProcStarted = ( - self.__testServerProc.waitForStarted()) + serverProcStarted = self.__testServerProc.waitForStarted() if not serverProcStarted: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django test server could not be' - ' started.')) - + self.tr("Process Generation Error"), + self.tr("The Django test server could not be" " started."), + ) + def __testServerProcFinished(self): """ Private slot connected to the finished signal of the test server. """ if ( - self.__testServerProc is not None and - self.__testServerProc.state() != QProcess.ProcessState.NotRunning + self.__testServerProc is not None + and self.__testServerProc.state() != QProcess.ProcessState.NotRunning ): self.__testServerProc.terminate() QTimer.singleShot(2000, self.__testServerProc.kill) self.__testServerProc.waitForFinished(3000) self.__testServerProc = None - + ################################################################## ## slots below implement authorization functions ################################################################## - + def __changePassword(self): """ Private slot to change the password of a user. """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommandNoClose"))[1] + self.__plugin.getPreferences("ConsoleCommandNoClose") + )[1] if consoleCmd: userName, ok = QInputDialog.getText( self.__ui, self.tr("Change Password"), self.tr("Enter the name of the user:"), - QLineEdit.EchoMode.Normal) + QLineEdit.EchoMode.Normal, + ) if ok and userName != "": args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) @@ -2959,84 +3192,84 @@ args.append("manage.py") args.append("changepassword") args.append(userName) - with contextlib.suppress(DjangoNoSiteSelectedException): + with contextlib.suppress(DjangoNoSiteSelectedError): wd = self.__sitePath() self.__adjustWorkingDirectory(args, wd) - started, pid = QProcess.startDetached( - args[0], args[1:], wd) + started, pid = QProcess.startDetached(args[0], args[1:], wd) if not started: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django process could not be' - ' started.')) - + self.tr("Process Generation Error"), + self.tr("The Django process could not be" " started."), + ) + def __createSuperUser(self): """ Private slot to create a super user account. """ consoleCmd = self.__isSpawningConsole( - self.__plugin.getPreferences("ConsoleCommandNoClose"))[1] + self.__plugin.getPreferences("ConsoleCommandNoClose") + )[1] if consoleCmd: args = Utilities.parseOptionString(consoleCmd) args[0] = Utilities.getExecutablePath(args[0]) args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("createsuperuser") - with contextlib.suppress(DjangoNoSiteSelectedException): + with contextlib.suppress(DjangoNoSiteSelectedError): wd = self.__sitePath() self.__adjustWorkingDirectory(args, wd) started, pid = QProcess.startDetached(args[0], args[1:], wd) if not started: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The Django process could not be started.')) - + self.tr("Process Generation Error"), + self.tr("The Django process could not be started."), + ) + ################################################################## ## slots below implement session functions ################################################################## - + def __clearSessions(self): """ Private slot to clear expired sessions. """ title = self.tr("Clear Sessions") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("clearsessions") - + dia = DjangoDialog( - title, - msgSuccess=self.tr("Expired sessions cleared successfully.")) + title, msgSuccess=self.tr("Expired sessions cleared successfully.") + ) res = dia.startProcess(args, wd) if res: dia.exec() - + ################################################################## ## slots below implement translation functions ################################################################## - + def __getLocale(self, filename): """ Private method to extract the locale out of a file name. - + @param filename name of the file used for extraction @type str @return extracted locale or None @rtype str """ if self.__ericProject.getTranslationPattern(): - pattern = ( - self.__ericProject.getTranslationPattern() - .replace("%language%", "(.*?)") + pattern = self.__ericProject.getTranslationPattern().replace( + "%language%", "(.*?)" ) match = re.search(pattern, filename) if match is not None: @@ -3046,13 +3279,13 @@ loc = None else: loc = None - + return loc - + def __normalizeList(self, filenames): """ Private method to normalize a list of file names. - + @param filenames list of file names to normalize @type list of str @return normalized file names @@ -3064,13 +3297,13 @@ filename = filename.replace(".mo", ".po") if filename not in nfilenames: nfilenames.append(filename) - + return nfilenames - + def __siteFilteredList(self, filenames): """ Private method to filter a list of file names by site. - + @param filenames list of file names to be filtered @type list of str @return file names belonging to the current site @@ -3081,74 +3314,72 @@ for filename in filenames: if site == "" or filename.startswith(site + os.sep): nfilenames.append(filename) - + return nfilenames - + def __projectLanguageAdded(self, code): """ Private slot handling the addition of a new language. - + @param code language code of the new language @type str """ - title = ( - self.tr("Initializing message catalog for '{0}'") - .format(code) - ) - + title = self.tr("Initializing message catalog for '{0}'").format(code) + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("makemessages") args.append("--locale={0}".format(code)) - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr( - "\nMessage catalog initialized successfully.")) + title, msgSuccess=self.tr("\nMessage catalog initialized successfully.") + ) res = dia.startProcess(args, wd) if res: dia.exec() - - langFile = ( - self.__ericProject.getTranslationPattern() - .replace("%language%", code) + + langFile = self.__ericProject.getTranslationPattern().replace( + "%language%", code ) self.__ericProject.appendFile(langFile) - + def updateSelectedCatalogs(self, filenames): """ Public method to update the message catalogs. - + @param filenames list of file names @type list of str """ title = self.tr("Updating message catalogs") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + argsLists = [] - - for filename in self.__normalizeList( - self.__siteFilteredList(filenames)): + + for filename in self.__normalizeList(self.__siteFilteredList(filenames)): locale = self.__getLocale(filename) if locale: args = [] @@ -3158,45 +3389,44 @@ args.append("--no-obsolete") args.append("--locale={0}".format(locale)) argsLists.append(args) - + if len(argsLists) == 0: EricMessageBox.warning( - None, - title, - self.tr('No locales detected. Aborting...')) + None, title, self.tr("No locales detected. Aborting...") + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr("\nMessage catalogs updated successfully.")) + title, msgSuccess=self.tr("\nMessage catalogs updated successfully.") + ) res = dia.startBatchProcesses(argsLists, wd) if res: dia.exec() - + def updateSelectedCatalogsWithObsolete(self, filenames): """ Public method to update the message catalogs keeping obsolete messages. - + @param filenames list of filenames @type list of str """ - title = self.tr("Updating message catalogs (keeping obsolete" - " messages)") - + title = self.tr("Updating message catalogs (keeping obsolete" " messages)") + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + argsLists = [] - - for filename in self.__normalizeList( - self.__siteFilteredList(filenames)): + + for filename in self.__normalizeList(self.__siteFilteredList(filenames)): locale = self.__getLocale(filename) if locale: args = [] @@ -3205,110 +3435,113 @@ args.append("makemessages") args.append("--locale={0}".format(locale)) argsLists.append(args) - + if len(argsLists) == 0: EricMessageBox.warning( - None, - title, - self.tr('No locales detected. Aborting...')) + None, title, self.tr("No locales detected. Aborting...") + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr("\nMessage catalogs updated successfully.")) + title, msgSuccess=self.tr("\nMessage catalogs updated successfully.") + ) res = dia.startBatchProcesses(argsLists, wd) if res: dia.exec() - + def updateCatalogs(self, filenames): """ Public method to update the message catalogs. - + @param filenames list of filenames (not used) @type list of str """ title = self.tr("Updating message catalogs") - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("makemessages") args.append("--all") args.append("--no-obsolete") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr("\nMessage catalogs updated successfully.")) + title, msgSuccess=self.tr("\nMessage catalogs updated successfully.") + ) res = dia.startProcess(args, wd) if res: dia.exec() - + def updateCatalogsWithObsolete(self, filenames): """ Public method to update the message catalogs keeping obsolete messages. - + @param filenames list of filenames (not used) @type list of str """ - title = self.tr("Updating message catalogs (keeping obsolete" - " messages)") - + title = self.tr("Updating message catalogs (keeping obsolete" " messages)") + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("makemessages") args.append("--all") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr("\nMessage catalogs updated successfully.")) + title, msgSuccess=self.tr("\nMessage catalogs updated successfully.") + ) res = dia.startProcess(args, wd) if res: dia.exec() - + def compileSelectedCatalogs(self, filenames): """ Public method to update the message catalogs. - + @param filenames list of filenames @type list of str """ title = self.tr("Compiling message catalogs") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + argsLists = [] - - for filename in self.__normalizeList( - self.__siteFilteredList(filenames)): + + for filename in self.__normalizeList(self.__siteFilteredList(filenames)): locale = self.__getLocale(filename) if locale: args = [] @@ -3319,72 +3552,71 @@ if self.__plugin.getPreferences("FuzzyTranslations"): args.append("--use-fuzzy") argsLists.append(args) - + if len(argsLists) == 0: EricMessageBox.warning( - None, - title, - self.tr('No locales detected. Aborting...')) + None, title, self.tr("No locales detected. Aborting...") + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr( - "\nMessage catalogs compiled successfully.")) + title, msgSuccess=self.tr("\nMessage catalogs compiled successfully.") + ) res = dia.startBatchProcesses(argsLists, wd, mergedOutput=True) if res: dia.exec() - + for entry in os.walk(self.__sitePath()): for fileName in entry[2]: fullName = os.path.join(entry[0], fileName) - if fullName.endswith('.mo'): + if fullName.endswith(".mo"): self.__ericProject.appendFile(fullName) - + def compileCatalogs(self, filenames): """ Public method to compile the message catalogs. - + @param filenames list of filenames (not used) @type list of str """ title = self.tr("Compiling message catalogs") - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") args.append("compilemessages") if self.__plugin.getPreferences("FuzzyTranslations"): args.append("--use-fuzzy") - + try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: EricMessageBox.warning( None, title, - self.tr('No current site selected or no site created yet.' - ' Aborting...')) + self.tr( + "No current site selected or no site created yet." " Aborting..." + ), + ) return - + dia = DjangoDialog( - title, - msgSuccess=self.tr( - "\nMessage catalogs compiled successfully.")) + title, msgSuccess=self.tr("\nMessage catalogs compiled successfully.") + ) res = dia.startProcess(args, wd, mergedOutput=True) if res: dia.exec() - + for entry in os.walk(self.__sitePath()): for fileName in entry[2]: fullName = os.path.join(entry[0], fileName) - if fullName.endswith('.mo'): + if fullName.endswith(".mo"): self.__ericProject.appendFile(fullName) - + def openPOEditor(self, poFile): """ Public method to edit the given file in an external .po editor. - + @param poFile name of the .po file @type str """ @@ -3392,33 +3624,37 @@ if poFile.endswith(".po") and editor: try: wd = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: wd = "" started, pid = QProcess.startDetached(editor, [poFile], wd) if not started: EricMessageBox.critical( None, - self.tr('Process Generation Error'), - self.tr('The translations editor process ({0}) could' - ' not be started.') - .format(os.path.basename(editor))) - + self.tr("Process Generation Error"), + self.tr( + "The translations editor process ({0}) could" " not be started." + ).format(os.path.basename(editor)), + ) + ################################################################## ## slots below implement check functions ################################################################## - + def __performCheck(self): """ Private slot to inspect the project for common problems. """ try: path = self.__sitePath() - except DjangoNoSiteSelectedException: + except DjangoNoSiteSelectedError: return - + from .DjangoCheckOptionsDialog import DjangoCheckOptionsDialog + dlg = DjangoCheckOptionsDialog( - self.__getPythonExecutable(), path, self.getRecentApplications(), + self.__getPythonExecutable(), + path, + self.getRecentApplications(), self.__plugin.getPreferences("CheckDeployMode"), ) if dlg.exec() == QDialog.DialogCode.Accepted: @@ -3427,7 +3663,7 @@ if appsStr != "": self.setMostRecentApplication(appsStr) apps = appsStr.split() - + args = [] args.append(self.__getPythonExecutable()) args.append("manage.py") @@ -3440,7 +3676,7 @@ if settingsFile: args.append("--settings={0}".format(settingsFile)) args += apps - + dia = DjangoDialog(self.tr("Check Project")) res = dia.startProcess(args, path, mergedOutput=True) if res: