[Checkins] SVN: Products.GenericSetup/branches/upgrade-upgrade-api/Products/GenericSetup/tool.py pyflakes, pep8

Godefroid Chapelle gotcha at bubblenet.be
Mon May 23 09:37:32 EDT 2011


Log message for revision 121782:
  pyflakes, pep8
    
  There is no pep8 compliant way of declaring security...
  So some complaints are left.
  
  

Changed:
  U   Products.GenericSetup/branches/upgrade-upgrade-api/Products/GenericSetup/tool.py

-=-
Modified: Products.GenericSetup/branches/upgrade-upgrade-api/Products/GenericSetup/tool.py
===================================================================
--- Products.GenericSetup/branches/upgrade-upgrade-api/Products/GenericSetup/tool.py	2011-05-23 13:32:29 UTC (rev 121781)
+++ Products.GenericSetup/branches/upgrade-upgrade-api/Products/GenericSetup/tool.py	2011-05-23 13:37:32 UTC (rev 121782)
@@ -25,7 +25,7 @@
 from OFS.Folder import Folder
 from OFS.Image import File
 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
-from zope import event 
+from zope import event
 from zope.interface import implements
 
 from Products.GenericSetup.context import DirectoryImportContext
@@ -59,6 +59,7 @@
 EXPORT_STEPS_XML = 'export_steps.xml'
 TOOLSET_XML = 'toolset.xml'
 
+
 def exportStepRegistries(context):
 
     """ Built-in handler for exporting import / export step registries.
@@ -82,6 +83,7 @@
     else:
         logger.debug('No local export steps.')
 
+
 def importToolset(context):
 
     """ Import required / forbidden tools from XML file.
@@ -136,6 +138,7 @@
 
     logger.info('Toolset imported.')
 
+
 def exportToolset(context):
 
     """ Export required / forbidden tools to XML file.
@@ -218,7 +221,7 @@
     security.declareProtected(ManagePortal, 'getExportStep')
     def getExportStep(self, step, default=None):
         """Simple wrapper to query both the global and local step registry."""
-        res=_export_step_registry.getStep(step, default)
+        res = _export_step_registry.getStep(step, default)
         if res is not default:
             return res
         return self._export_registry.getStep(step, default)
@@ -232,7 +235,7 @@
     security.declareProtected(ManagePortal, 'getImportStep')
     def getImportStep(self, step, default=None):
         """Simple wrapper to query both the global and local step registry."""
-        res=_import_step_registry.getStep(step, default)
+        res = _import_step_registry.getStep(step, default)
         if res is not default:
             return res
         return self._import_registry.getStep(step, default)
@@ -241,14 +244,14 @@
     def getSortedImportSteps(self):
         steps = _import_step_registry.listSteps() + \
                 self._import_registry.listSteps()
-        step_infos = [ self.getImportStepMetadata(step)
-                       for step in set(steps) ]
+        step_infos = [self.getImportStepMetadata(step)
+                       for step in set(steps)]
         return tuple(_computeTopologicalSort(step_infos))
 
     security.declareProtected(ManagePortal, 'getImportStepMetadata')
     def getImportStepMetadata(self, step, default=None):
         """Simple wrapper to query both the global and local step registry."""
-        res=self._import_registry.getStepMetadata(step, default)
+        res = self._import_registry.getStepMetadata(step, default)
         if res is not default:
             return res
         return _import_step_registry.getStepMetadata(step, default)
@@ -256,7 +259,7 @@
     security.declareProtected(ManagePortal, 'getExportStepMetadata')
     def getExportStepMetadata(self, step, default=None):
         """Simple wrapper to query both the global and local step registry."""
-        res=self._export_registry.getStepMetadata(step, default)
+        res = self._export_registry.getStepMetadata(step, default)
         if res is not default:
             return res
         return _export_step_registry.getStepMetadata(step, default)
@@ -279,7 +282,7 @@
         info = self.getImportStepMetadata(step_id)
 
         if info is None:
-            raise ValueError, 'No such import step: %s' % step_id
+            raise ValueError('No such import step: %s' % step_id)
 
         dependencies = info.get('dependencies', ())
 
@@ -290,22 +293,24 @@
             for dependency in dependencies:
                 if dependency not in steps:
                     steps.append(dependency)
-        steps.append (step_id)
+        steps.append(step_id)
 
-        full_import=(set(steps)==set(self.getSortedImportSteps()))
-        event.notify(BeforeProfileImportEvent(self, profile_id, steps, full_import))
+        full_import = (set(steps) == set(self.getSortedImportSteps()))
+        event.notify(BeforeProfileImportEvent(self, profile_id, steps,
+            full_import))
 
         for step in steps:
             message = self._doRunImportStep(step, context)
             messages[step] = message or ''
 
         message_list = filter(None, [message])
-        message_list.extend( ['%s: %s' % x[1:] for x in context.listNotes()] )
+        message_list.extend(['%s: %s' % x[1:] for x in context.listNotes()])
         messages[step_id] = '\n'.join(message_list)
 
-        event.notify(ProfileImportedEvent(self, profile_id, steps, full_import))
+        event.notify(ProfileImportedEvent(self, profile_id, steps,
+            full_import))
 
-        return { 'steps' : steps, 'messages' : messages }
+        return {'steps': steps, 'messages': messages}
 
     security.declareProtected(ManagePortal, 'runAllImportStepsFromProfile')
     def runAllImportStepsFromProfile(self,
@@ -318,9 +323,8 @@
         __traceback_info__ = profile_id
 
         result = self._runImportStepsFromContext(purge_old=purge_old,
-                                                 profile_id=profile_id,
-                                                 archive=archive,
-                                                 ignore_dependencies=ignore_dependencies)
+            profile_id=profile_id, archive=archive,
+            ignore_dependencies=ignore_dependencies)
         if profile_id is None:
             prefix = 'import-all-from-tar'
         else:
@@ -361,13 +365,10 @@
 
             messages[step_id] = handler(context)
 
+        return {'steps': steps, 'messages': messages,
+            'url': context.getSnapshotURL(),
+            'snapshot': context.getSnapshotFolder()}
 
-        return { 'steps' : steps
-               , 'messages' : messages
-               , 'url' : context.getSnapshotURL()
-               , 'snapshot' : context.getSnapshotFolder()
-               }
-
     security.declareProtected(ManagePortal, 'compareConfigurations')
     def compareConfigurations(self,
                               lhs_context,
@@ -375,7 +376,7 @@
                               missing_as_empty=False,
                               ignore_blanks=False,
                               skip=SKIPPED_FILES,
-                             ):
+                            ):
         """ See ISetupTool.
         """
         differ = ConfigDiff(lhs_context,
@@ -383,7 +384,7 @@
                             missing_as_empty,
                             ignore_blanks,
                             skip,
-                           )
+                          )
 
         return differ.compare()
 
@@ -438,30 +439,30 @@
     #   ZMI
     #
     manage_options = (Folder.manage_options[:1]
-                    + ({'label' : 'Profiles',
-                        'action' : 'manage_tool'
+                    + ({'label': 'Profiles',
+                        'action': 'manage_tool'
+                      },
+                       {'label': 'Import',
+                        'action': 'manage_importSteps'
+                      },
+                       {'label': 'Export',
+                        'action': 'manage_exportSteps'
+                      },
+                       {'label': 'Upgrades',
+                        'action': 'manage_upgrades'
                        },
-                       {'label' : 'Import',
-                        'action' : 'manage_importSteps'
-                       },
-                       {'label' : 'Export',
-                        'action' : 'manage_exportSteps'
-                       },
-                       {'label' : 'Upgrades',
-                        'action' : 'manage_upgrades'
-                        },
-                       {'label' : 'Snapshots',
-                        'action' : 'manage_snapshots'
-                       },
-                       {'label' : 'Comparison',
-                        'action' : 'manage_showDiff'
-                       },
-                       {'label' : 'Manage',
-                        'action' : 'manage_stepRegistry'
-                       },
-                      )
-                    + Folder.manage_options[3:] # skip "View", "Properties"
+                       {'label': 'Snapshots',
+                        'action': 'manage_snapshots'
+                      },
+                       {'label': 'Comparison',
+                        'action': 'manage_showDiff'
+                      },
+                       {'label': 'Manage',
+                        'action': 'manage_stepRegistry'
+                      },
                      )
+                    + Folder.manage_options[3:]  # skip "View", "Properties"
+                    )
 
     security.declareProtected(ManagePortal, 'manage_tool')
     manage_tool = PageTemplateFile('sutProperties', _wwwdir)
@@ -479,7 +480,8 @@
     manage_importSteps = PageTemplateFile('sutImportSteps', _wwwdir)
 
     security.declareProtected(ManagePortal, 'manage_importSelectedSteps')
-    def manage_importSelectedSteps(self, ids, run_dependencies, context_id=None):
+    def manage_importSelectedSteps(self, ids, run_dependencies,
+        context_id=None):
         """ Import the steps selected by the user.
         """
         messages = {}
@@ -529,7 +531,7 @@
                                   % (self.absolute_url(), message))
         else:
             message = 'Imported profiles: %s' % ', '.join(profile_ids)
-        
+
             for profile_id in profile_ids:
 
                 result = self.runAllImportStepsFromProfile(profile_id)
@@ -606,13 +608,9 @@
         snapshots = self._getOb('snapshots', None)
 
         if snapshots:
-
             for id, folder in snapshots.objectItems('Folder'):
-
-                result.append({ 'id' : id
-                               , 'title' : folder.title_or_id()
-                               , 'url' : folder.absolute_url()
-                               })
+                result.append({'id': id, 'title': folder.title_or_id(),
+                    'url': folder.absolute_url()})
         return result
 
     security.declareProtected(ManagePortal, 'listProfileInfo')
@@ -656,13 +654,13 @@
         s_infos = [{'id': 'snapshot-%s' % info['id'],
                      'title': info['title'],
                      'type': 'snapshot',
-                   }
+                  }
                     for info in self.listSnapshotInfo()]
         s_infos.sort(key=itemgetter('title'))
         p_infos = [{'id': 'profile-%s' % info['id'],
                     'title': info['title'],
                     'type': readableType(info['type']),
-                   }
+                  }
                    for info in self.listProfileInfo()]
         p_infos.sort(key=itemgetter('title'))
 
@@ -674,7 +672,7 @@
         """
         prefix = ('import-all-%s-' % profile_id).replace(':', '_')
         candidates = [x for x in self.objectIds('File')
-                        if x[:-18]==prefix and x.endswith('.log')]
+                        if x[:-18] == prefix and x.endswith('.log')]
         if len(candidates) == 0:
             return None
         candidates.sort()
@@ -686,7 +684,7 @@
                                        stamp[8:10],
                                        stamp[10:12],
                                        stamp[12:14],
-                                      )
+                                     )
 
     security.declareProtected(ManagePortal, 'manage_createSnapshot')
     def manage_createSnapshot(self, RESPONSE, snapshot_id=None):
@@ -711,7 +709,7 @@
                             missing_as_empty,
                             ignore_blanks,
                             RESPONSE,
-                           ):
+                          ):
         """ Crack request vars and call compareConfigurations.
 
         o Return the result as a 'text/plain' stream, suitable for framing.
@@ -720,7 +718,7 @@
                                                        rhs,
                                                        missing_as_empty,
                                                        ignore_blanks,
-                                                      )
+                                                     )
         RESPONSE.setHeader('Content-Type', 'text/plain')
         return _PLAINTEXT_DIFF_HEADER % (lhs, rhs, comparison)
 
@@ -730,7 +728,7 @@
                                      rhs,
                                      missing_as_empty,
                                      ignore_blanks,
-                                    ):
+                                   ):
         """ Crack request vars and call compareConfigurations.
         """
         lhs_context = self._getImportContext(lhs)
@@ -740,7 +738,7 @@
                                           rhs_context,
                                           missing_as_empty,
                                           ignore_blanks,
-                                         )
+                                        )
 
     security.declareProtected(ManagePortal, 'manage_stepRegistry')
     manage_stepRegistry = PageTemplateFile('sutManage', _wwwdir)
@@ -751,7 +749,7 @@
             request = self.REQUEST
         for id in ids:
             self._import_registry.unregisterStep(id)
-        self._p_changed=True
+        self._p_changed = True
         url = self.absolute_url()
         request.RESPONSE.redirect("%s/manage_stepRegistry" % url)
 
@@ -761,7 +759,7 @@
             request = self.REQUEST
         for id in ids:
             self._export_registry.unregisterStep(id)
-        self._p_changed=True
+        self._p_changed = True
         url = self.absolute_url()
         request.RESPONSE.redirect("%s/manage_stepRegistry" % url)
 
@@ -790,13 +788,13 @@
         """Return the registered filesystem version for the specified
         profile.
         """
-        return self.getProfileInfo( profile_id ).get('version', 'unknown')
+        return self.getProfileInfo(profile_id).get('version', 'unknown')
 
     security.declareProtected(ManagePortal, 'profileExists')
     def profileExists(self, profile_id):
         """Check if a profile exists."""
         try:
-            self.getProfileInfo( profile_id )
+            self.getProfileInfo(profile_id)
         except KeyError:
             return False
         else:
@@ -815,10 +813,10 @@
         if profile_id.startswith("snapshot-"):
             return ()
 
-        if not self.profileExists( profile_id ):
-            raise KeyError, profile_id
+        if not self.profileExists(profile_id):
+            raise KeyError(profile_id)
         try:
-            return self.getProfileInfo( profile_id ).get('dependencies', ())
+            return self.getProfileInfo(profile_id).get('dependencies', ())
         except KeyError:
             return ()
 
@@ -883,7 +881,8 @@
             self.setLastVersionForProfile(profile_id, step.dest)
 
         url = self.absolute_url()
-        request.RESPONSE.redirect("%s/manage_upgrades?saved=%s" % (url, profile_id))
+        request.RESPONSE.redirect("%s/manage_upgrades?saved=%s" %
+            (url, profile_id))
 
     #
     #   Helper methods
@@ -900,28 +899,30 @@
                 info = _profile_registry.getProfileInfo(context_id)
 
                 if info.get('product'):
-                    path = os.path.join(_getProductPath(info['product'])
-                                       , info['path'])
+                    path = os.path.join(_getProductPath(info['product']),
+                        info['path'])
                 else:
                     path = info['path']
                 if should_purge is None:
                     should_purge = (info.get('type') != EXTENSION)
-                return DirectoryImportContext(self, path, should_purge, encoding)
+                return DirectoryImportContext(self, path, should_purge,
+                    encoding)
 
             elif context_id.startswith('snapshot-'):
                 context_id = context_id[len('snapshot-'):]
                 if should_purge is None:
                     should_purge = True
-                return SnapshotImportContext(self, context_id, should_purge, encoding)
+                return SnapshotImportContext(self, context_id, should_purge,
+                    encoding)
 
         if archive is not None:
             return TarballImportContext(tool=self,
                                        archive_bits=archive,
                                        encoding='UTF8',
                                        should_purge=should_purge,
-                                      )
+                                     )
 
-        raise KeyError, 'Unknown context "%s"' % context_id
+        raise KeyError('Unknown context "%s"' % context_id)
 
     security.declarePrivate('_updateImportStepsRegistry')
     def _updateImportStepsRegistry(self, context, encoding):
@@ -948,7 +949,7 @@
                                                dependencies=dependencies,
                                                title=title,
                                                description=description,
-                                              )
+                                             )
 
     security.declarePrivate('_updateExportStepsRegistry')
     def _updateExportStepsRegistry(self, context, encoding):
@@ -971,7 +972,7 @@
                                                handler=handler,
                                                title=title,
                                                description=description,
-                                              )
+                                             )
 
     security.declarePrivate('_doRunImportStep')
     def _doRunImportStep(self, step_id, context):
@@ -1016,24 +1017,22 @@
             else:
                 messages[step_id] = handler(context)
 
-        return { 'steps' : steps
-               , 'messages' : messages
-               , 'tarball' : context.getArchive()
-               , 'filename' : context.getArchiveFilename()
-               }
+        return {'steps': steps, 'messages': messages,
+            'tarball': context.getArchive(),
+            'filename': context.getArchiveFilename()}
 
     security.declareProtected(ManagePortal, 'getProfileDependencyChain')
     def getProfileDependencyChain(self, profile_id, seen=None):
         if seen is None:
             seen = set()
         elif profile_id in seen:
-            return [] # cycle break
-        seen.add( profile_id )
+            return []  # cycle break
+        seen.add(profile_id)
         chain = []
 
-        dependencies = self.getDependenciesForProfile( profile_id )
+        dependencies = self.getDependenciesForProfile(profile_id)
         for dependency in dependencies:
-            chain.extend(self.getProfileDependencyChain( dependency, seen ))
+            chain.extend(self.getProfileDependencyChain(dependency, seen))
 
         chain.append(profile_id)
 
@@ -1049,19 +1048,18 @@
                                    seen=None):
 
         if profile_id is not None and not ignore_dependencies:
-            try: 
-                chain = self.getProfileDependencyChain( profile_id )
+            try:
+                chain = self.getProfileDependencyChain(profile_id)
             except KeyError, e:
                 logger = logging.getLogger('GenericSetup')
                 logger.error('Unknown step in dependency chain: %s' % str(e))
                 raise
         else:
-            chain = [ profile_id ]
+            chain = [profile_id]
             if seen is None:
-                seen=set()
-            seen.add( profile_id )
+                seen = set()
+            seen.add(profile_id)
 
-        
         results = []
 
         detect_steps = steps is None
@@ -1075,20 +1073,21 @@
 
             messages = {}
 
-            event.notify(BeforeProfileImportEvent(self, profile_id, steps, True))
+            event.notify(BeforeProfileImportEvent(self, profile_id, steps,
+                True))
             for step in steps:
                 message = self._doRunImportStep(step, context)
                 message_list = filter(None, [message])
-                message_list.extend( ['%s: %s' % x[1:]
-                                      for x in context.listNotes()] )
+                message_list.extend(['%s: %s' % x[1:]
+                                      for x in context.listNotes()])
                 messages[step] = '\n'.join(message_list)
                 context.clearNotes()
 
             event.notify(ProfileImportedEvent(self, profile_id, steps, True))
 
-            results.append({'steps' : steps, 'messages' : messages })
+            results.append({'steps': steps, 'messages': messages})
 
-        data = { 'steps' : [], 'messages' : {}}
+        data = {'steps': [], 'messages': {}}
         for result in results:
             for step in result['steps']:
                 if step not in data['steps']:
@@ -1096,9 +1095,9 @@
 
             for (step, msg) in result['messages'].items():
                 if step in data['messages']:
-                    data['messages'][step]+="\n"+msg
+                    data['messages'][step] += "\n" + msg
                 else:
-                    data['messages'][step]=msg
+                    data['messages'][step] = msg
         data['steps'] = list(data['steps'])
 
         return data
@@ -1150,14 +1149,14 @@
                     title='',
                     file=report,
                     content_type='text/plain'
-                   )
+                  )
 
         self._setObject(name, file)
 
 InitializeClass(SetupTool)
 
 
-_PLAINTEXT_DIFF_HEADER ="""\
+_PLAINTEXT_DIFF_HEADER = """\
 Comparing configurations: '%s' and '%s'
 
 %s"""
@@ -1166,6 +1165,7 @@
 
 addSetupToolForm = PageTemplateFile('toolAdd.zpt', _wwwdir)
 
+
 def addSetupTool(dispatcher, RESPONSE):
     """
     """



More information about the checkins mailing list