PluginToolGenerateHash.py

branch
eric7
changeset 61
6fc29f5292d3
parent 59
992bee3beceb
child 62
3d0bb45398c6
diff -r d3a8515784ec -r 6fc29f5292d3 PluginToolGenerateHash.py
--- a/PluginToolGenerateHash.py	Thu Dec 30 14:32:30 2021 +0100
+++ b/PluginToolGenerateHash.py	Wed Sep 21 11:03:37 2022 +0200
@@ -43,41 +43,53 @@
     """
     Class implementing the 'Generate Hash' tool plug-in.
     """
+
     Hashes = [
-        h for h in ("md5", "sha1", "sha224", "sha256", "sha384", "sha512",
-                    "sha3_224", "sha3_256", "sha3_384", "sha3_512")
+        h
+        for h in (
+            "md5",
+            "sha1",
+            "sha224",
+            "sha256",
+            "sha384",
+            "sha512",
+            "sha3_224",
+            "sha3_256",
+            "sha3_384",
+            "sha3_512",
+        )
         if h in hashlib.algorithms_guaranteed
     ]
-    
+
     def __init__(self, ui):
         """
         Constructor
-        
+
         @param ui reference to the user interface object (UI.UserInterface)
         """
         super().__init__(ui)
         self.__ui = ui
-        
+
         self.__translator = None
         self.__loadTranslator()
-        
+
         self.__initMenus()
-        
+
         self.__editors = {}
         self.__mainActions = []
-    
+
     def activate(self):
         """
         Public method to activate this plugin.
-        
+
         @return tuple of None and activation status
         @rtype bool
         """
         global error
-        error = ""     # clear previous error
-        
+        error = ""  # clear previous error
+
         self.__ui.showMenu.connect(self.__populateMenu)
-        
+
         menu = self.__ui.getMenu("plugin_tools")
         if menu is not None:
             if not menu.isEmpty():
@@ -87,23 +99,21 @@
             self.__mainActions.append(act)
             act = menu.addMenu(self.__dirMenu)
             self.__mainActions.append(act)
-        
-        ericApp().getObject("ViewManager").editorOpenedEd.connect(
-            self.__editorOpened)
-        ericApp().getObject("ViewManager").editorClosedEd.connect(
-            self.__editorClosed)
-        
+
+        ericApp().getObject("ViewManager").editorOpenedEd.connect(self.__editorOpened)
+        ericApp().getObject("ViewManager").editorClosedEd.connect(self.__editorClosed)
+
         for editor in ericApp().getObject("ViewManager").getOpenEditors():
             self.__editorOpened(editor)
-        
+
         return None, True
-    
+
     def deactivate(self):
         """
         Public method to deactivate this plugin.
         """
         self.__ui.showMenu.disconnect(self.__populateMenu)
-        
+
         menu = self.__ui.getMenu("plugin_tools")
         if menu is not None:
             for act in self.__mainActions:
@@ -111,10 +121,12 @@
         self.__mainActions = []
 
         ericApp().getObject("ViewManager").editorOpenedEd.disconnect(
-            self.__editorOpened)
+            self.__editorOpened
+        )
         ericApp().getObject("ViewManager").editorClosedEd.disconnect(
-            self.__editorClosed)
-        
+            self.__editorClosed
+        )
+
         for editor, acts in self.__editors.items():
             editor.showMenu.disconnect(self.__editorShowMenu)
             menu = editor.getMenu("Tools")
@@ -122,7 +134,7 @@
                 for act in acts:
                     menu.removeAction(act)
         self.__editors = {}
-    
+
     def __loadTranslator(self):
         """
         Private method to load the translation file.
@@ -131,7 +143,8 @@
             loc = self.__ui.getLocale()
             if loc and loc != "C":
                 locale_dir = os.path.join(
-                    os.path.dirname(__file__), "ToolGenerateHash", "i18n")
+                    os.path.dirname(__file__), "ToolGenerateHash", "i18n"
+                )
                 translation = "generatehash_{0}".format(loc)
                 translator = QTranslator(None)
                 loaded = translator.load(translation, locale_dir)
@@ -139,32 +152,36 @@
                     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 __initMenus(self):
         """
         Private method to initialize the hash generation menus.
         """
         self.__fileMenu = QMenu(self.tr("Generate File Hash"))
         for hashName in self.Hashes:
-            self.__fileMenu.addAction(
-                hashName.upper().replace("_", ":")).setData(hashName)
+            self.__fileMenu.addAction(hashName.upper().replace("_", ":")).setData(
+                hashName
+            )
         self.__fileMenu.setEnabled(False)
         self.__fileMenu.triggered.connect(self.__hashFile)
-        
+
         self.__dirMenu = QMenu(self.tr("Generate Directory Hash"))
         for hashName in self.Hashes:
-            self.__dirMenu.addAction(
-                hashName.upper().replace("_", ":")).setData(hashName)
+            self.__dirMenu.addAction(hashName.upper().replace("_", ":")).setData(
+                hashName
+            )
         self.__dirMenu.setEnabled(False)
         self.__dirMenu.triggered.connect(self.__hashDirectory)
-    
+
     def __populateMenu(self, name, menu):
         """
         Private slot to populate the tools menu with our entries.
-        
+
         @param name name of the menu
         @type str
         @param menu reference to the menu to be populated
@@ -172,13 +189,13 @@
         """
         if name not in ["Tools", "PluginTools"]:
             return
-        
+
         editor = ericApp().getObject("ViewManager").activeWindow()
-        
+
         if name == "Tools":
             if not menu.isEmpty():
                 menu.addSeparator()
-            
+
             act = menu.addMenu(self.__fileMenu)
             act.setEnabled(editor is not None)
             act = menu.addMenu(self.__dirMenu)
@@ -186,11 +203,11 @@
         elif name == "PluginTools" and self.__mainActions:
             self.__mainActions[-2].setEnabled(editor is not None)
             self.__mainActions[-1].setEnabled(editor is not None)
-    
+
     def __editorOpened(self, editor):
         """
         Private slot called, when a new editor was opened.
-        
+
         @param editor reference to the new editor
         @type Editor
         """
@@ -205,14 +222,14 @@
             act = menu.addMenu(self.__dirMenu)
             self.__editors[editor].append(act)
             editor.showMenu.connect(self.__editorShowMenu)
-            
+
             self.__fileMenu.setEnabled(True)
             self.__dirMenu.setEnabled(True)
-    
+
     def __editorClosed(self, editor):
         """
         Private slot called, when an editor was closed.
-        
+
         @param editor reference to the editor
         @type Editor
         """
@@ -221,12 +238,12 @@
             if not self.__editors:
                 self.__fileMenu.setEnabled(False)
                 self.__dirMenu.setEnabled(False)
-    
+
     def __editorShowMenu(self, menuName, menu, editor):
         """
         Private slot called, when the the editor context menu or a submenu is
         about to be shown.
-        
+
         @param menuName name of the menu to be shown
         @type str
         @param menu reference to the menu
@@ -234,10 +251,7 @@
         @param editor reference to the editor
         @type Editor
         """
-        if (
-            menuName == "Tools" and
-            self.__fileMenu.menuAction() not in menu.actions()
-        ):
+        if menuName == "Tools" and self.__fileMenu.menuAction() not in menu.actions():
             # Re-add our menu
             self.__editors[editor] = []
             if not menu.isEmpty():
@@ -247,14 +261,14 @@
             self.__editors[editor].append(act)
             act = menu.addMenu(self.__dirMenu)
             self.__editors[editor].append(act)
-            
+
             self.__fileMenu.setEnabled(True)
             self.__dirMenu.setEnabled(True)
-    
+
     def __insertHash(self, hashStr):
         """
         Private method to insert the generated hash string.
-        
+
         @param hashStr hash string
         @type str
         """
@@ -265,21 +279,19 @@
             editor.beginUndoAction()
             editor.insertAt(hashStr, line, index)
             editor.endUndoAction()
-    
+
     @pyqtSlot(QAction)
     def __hashFile(self, act):
         """
         Private slot to generate the hash for a file.
-        
+
         @param act reference to the action that was triggered
         @type QAction
         """
         if act is None:
             return
-        
-        name = EricFileDialog.getOpenFileName(
-            self.__ui,
-            self.tr("Generate File Hash"))
+
+        name = EricFileDialog.getOpenFileName(self.__ui, self.tr("Generate File Hash"))
         if name:
             try:
                 with open(name, "rb") as f:
@@ -288,42 +300,39 @@
                 EricMessageBox.critical(
                     self.__ui,
                     self.tr("Generate File Hash"),
-                    self.tr("""<p>The hash for <b>{0}</b> could not"""
-                            """ be generated.</p><p>Reason: {1}</p>""")
-                    .format(name, str(err))
+                    self.tr(
+                        """<p>The hash for <b>{0}</b> could not"""
+                        """ be generated.</p><p>Reason: {1}</p>"""
+                    ).format(name, str(err)),
                 )
                 return
-            
+
             self.__insertHash(hashStr)
-    
+
     @pyqtSlot(QAction)
     def __hashDirectory(self, act):
         """
         Private slot to generate the hash for a directory.
-        
+
         @param act reference to the action that was triggered
         @type QAction
         """
         if act is None:
             return
-        
+
         folder = EricFileDialog.getExistingDirectory(
-            self.__ui,
-            self.tr("Generate Directory Hash"),
-            "",
-            EricFileDialog.Option(0))
+            self.__ui, self.tr("Generate Directory Hash"), "", EricFileDialog.Option(0)
+        )
         if folder and os.path.isdir(folder):
             fails = 0
             hashes = []
             for name in os.listdir(folder):
-                if (
-                    not name.startswith(".") and
-                    os.path.isfile(os.path.join(folder, name))
+                if not name.startswith(".") and os.path.isfile(
+                    os.path.join(folder, name)
                 ):
                     try:
                         with open(os.path.join(folder, name), "rb") as f:
-                            hashStr = hashlib.new(
-                                act.data(), f.read()).hexdigest()
+                            hashStr = hashlib.new(act.data(), f.read()).hexdigest()
                         hashes.append((name, hashStr))
                     except OSError:
                         fails += 1
@@ -331,26 +340,27 @@
                 EricMessageBox.critical(
                     self.__ui,
                     self.tr("Generate Directory Hash"),
-                    self.tr("""<p>The hash for some files could not"""
-                            """ be generated.</p>""")
+                    self.tr(
+                        """<p>The hash for some files could not"""
+                        """ be generated.</p>"""
+                    ),
                 )
             else:
                 editor = ericApp().getObject("ViewManager").activeWindow()
                 line, index = editor.getCursorPosition()
-                indLevel = (editor.indentation(line) //
-                            editor.indentationWidth())
+                indLevel = editor.indentation(line) // editor.indentationWidth()
                 if editor.indentationsUseTabs():
-                    indString = '\t'
+                    indString = "\t"
                 else:
-                    indString = editor.indentationWidth() * ' '
+                    indString = editor.indentationWidth() * " "
                 indent = (indLevel + 1) * indString
                 code = ["["]
                 for name, hashStr in hashes:
-                    code.append("{0}('{1}', '{2}'),".format(
-                        indent, name, hashStr))
+                    code.append("{0}('{1}', '{2}'),".format(indent, name, hashStr))
                 code.append("{0}]".format(indLevel * indString))
-                
+
                 self.__insertHash(os.linesep.join(code))
 
+
 #
 # eflag: noqa = M801

eric ide

mercurial