1. Georg Brandl
  2. sphinx-contrib

Commits

diabeteman  committed 03c94dd

fixed errors on columns widths resolution when some fields are NULL.
fixed broken tables when some columns are "not shown"
removed explicit dependency to "pywin32" to avoid crashes of easy_install.

  • Participants
  • Parent commits 9148306
  • Branches default
  • Tags clearquest-0.2

Comments (0)

Files changed (5)

File clearquest/CHANGES

View file
+.. -*- restructuredtext -*-
+
+This file describes user-visible changes between the extension versions.
+
+
+
+
+Version 0.2 (2011-12-14)
+------------------------
+
+* fixed errors on columns widths resolution when some fields are NULL.
+* fixed broken tables when some columns are "not shown"
+* removed explicit dependency to "pywin32" to avoid crashes of easy_install.
+
+
+Version 0.1 (2011-12-13)
+------------------------
+
+* Initial version.

File clearquest/README

View file
 Sphinx "ClearQuest" extension 
 =============================
 
+Description
+===========
+
 A sphinx extension that adds a ``clearquest`` directive for converting 
 ClearQuest__ requests to reStructuredText tables.
 
 __ http://www-01.ibm.com/software/awdtools/clearquest/
 
-Syntax
-------
+Dependencies
+============
+
+Sphinx
+   http://sphinx.pocoo.org/
+PyWin32
+   http://sourceforge.net/projects/pywin32/ (**PyWin32** will not be automatically 
+   installed by ``easy_install`` or ``pip install`` as ``egg`` packages are not
+   available on **pypi**)
+
+Installation & Usage
+====================
+
+You can install the ``sphinxcontrib.clearquest`` package with ``easy_install`` 
+or ``pip``: ::
+
+   $ easy_install sphinxcontrib-clearquest
+
+Or with the windows installer available on this page.
+
+.. important:: You must manually install **PyWin32** for the directive to work.
+
+Append ``'sphinxcontrib.clearquest'`` to extensions parameter, and run Sphinx.
+
+Directive Syntax
+================
 
 The syntax of the directive is as follows: ::
 
-    .. clearquest:: <full name/of the clearquest query> (mandatory)
-        :username: <your username> (optional)
-        :password: <your password> (optional)
-        :db_name: <the name of the db> (optional)
-        :db_set: <the name of the db set> (optional)
-        :params: <parameters to pass to the query> (optional)
-
-The connection credentials can either be provided as directive options or 
-in a ``clearquest`` section in the ``~/.sphinxcontrib`` file which is a 
-standard ``.ini`` configuration file. ::
-
-	[clearquest]
-	username = john
-	password = doe
-	db_name = prod
-	db_set = cqsrv
+   .. clearquest:: <full name/of the clearquest query> (mandatory)
+      :params: <parameters to pass to the query> (optional)
+      :username: <your username> (optional)
+      :password: <your password> (optional)
+      :db_name: <the name of the db> (optional)
+      :db_set: <the name of the db set> (optional)
 
 The parameters to pass to the query must respect the following syntax: ::
 
-    <param1_name>=<param1_value>,<param2_name>=<param2_value>, ....
+   <param1_name>=<param1_value>,<param2_name>=<param2_value>, ...
 
 You can provide them in any order as long as you don't forget one. 
 The query call will fail if you do.
 
-Required python libraries
--------------------------
+The connection credentials can either be provided as directive options or 
+in a ``clearquest`` section in the ``~/.sphinxcontrib`` file which is a 
+standard ``.ini`` configuration file. 
 
-* sphinx: http://sphinx.pocoo.org/
-* PyWin32: http://sourceforge.net/projects/pywin32/
+Here is an example of ``~/.sphinxcontrib`` file: ::
+
+   [clearquest]
+   username = john
+   password = doe
+   db_name = prod
+   db_set = cqsrv
+

File clearquest/setup.py

View file
 #!/usr/bin/env python
-# -*- coding: utf-8 -*-
 
 from setuptools import setup, find_packages
 
 long_desc = open('README', 'r').read()
 
-requires = ['Sphinx>=0.6', 'pywin32']
+# We need 'pywin32' too but it is not available on pypi.
+# To avoid crashes of easy_install and pip, I removed the dependency here.
+requires = ['Sphinx>=0.6']
 
 setup(
     name='sphinxcontrib-clearquest',
-    version='0.1',
+    version='0.2',
     url='http://bitbucket.org/birkenfeld/sphinx-contrib',
     download_url='http://pypi.python.org/pypi/sphinxcontrib-clearquest',
     license='BSD',

File clearquest/sphinxcontrib/clearquest/connection.py

View file
 # Copyright (c) 2009 by the contributors (see AUTHORS file).
 # All rights reserved.
-# 
+#
 # Redistribution and use in source and binary forms, with or without
 # modification, are permitted provided that the following conditions are
 # met:
-# 
+#
 # * Redistributions of source code must retain the above copyright
 #   notice, this list of conditions and the following disclaimer.
-# 
+#
 # * Redistributions in binary form must reproduce the above copyright
 #   notice, this list of conditions and the following disclaimer in the
 #   documentation and/or other materials provided with the distribution.
-# 
+#
 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
         self.password = str(password)
         self.db_name = str(db_name)
         self.db_set = str(db_set)
+        #self.db_encoding = str(db_encoding)
         self.session = None
-    
+
     def run_query(self, queryName, parameters):
         """
         Runs a ClearQuest query and returns the result as a list of lists.
-        
+
         example:
 
         [ ['column_1',  'column_2',  'column_3'],
           ['value_2_1', 'value_2_2', 'value_2_3'],
           ['value_3_1', 'value_3_2', 'value_3_3'],
           ['value_4_1', 'value_4_2', 'value_4_3'], ]
-          
+
         If the query returns nothing, only one row containing dashes is returned.
-        
+
         """
         if self.session is None:
             self.open_session()
-        
+
         workspace = self.session.GetWorkSpace
         query = workspace.GetQueryDef(queryName)
         resultSet = self.session.BuildResultSet(query)
         numberOfParams = resultSet.GetNumberOfParams
-        
+
         if numberOfParams:
             errors = []
-            
+
             for i in range(1, numberOfParams + 1):
                 param_name = resultSet.GetParamLabel(i)
                 try:
                 except:
                     errors.append("'%s'" % param_name)
                 resultSet.AddParamValue(i, param_value)
-            
+
             if errors:
-                params = ", ".join(errors) 
+                params = ", ".join(errors)
                 raise ValueError("Missing parameters %s to query '%s'" % (params, queryName))
-            
+
         resultSet.Execute()
-        
+
         status = resultSet.MoveNext
-        
+
         # this is silly, but first column is reserved
         nbcol = resultSet.GetNumberOfColumns - 1
-        
+
         records = []
-        columns = [ fieldDef.Label for fieldDef in query.QueryFieldDefs ][1:]
-        
+        columns = [ field.Label for field in query.QueryFieldDefs if field.IsShown ][1:]
+
         if status != 1:
             # No results from ClearQuest query, we fill one line with dashes
             records.append(list("-" * len(columns)))
-            
+
         while status == 1:
             records.append([ resultSet.GetColumnValue(i) for i in range(2, nbcol + 2) ])
             status = resultSet.MoveNext
-            
+
+        #return self.convert_to_utf8(columns, records)
         return columns, records
-    
+
     def open_session(self):
         self.session = COM.dynamic.Dispatch("CLEARQUEST.SESSION")
-        self.session.UserLogon(self.username, self.password, self.db_name, 
+        self.session.UserLogon(self.username, self.password, self.db_name,
                                PRIVATE_SESSION, self.db_set)
 
+#    def convert_to_utf8(self, columns, records):
+#        if self.db_encoding != 'utf-8':
+#            utf8_columns = []
+#            for col in columns:
+#                encoded_str = col.encode(self.db_encoding, 'xmlcharrefreplace')
+#                utf8_columns.append(encoded_str.decode('utf-8', 'replace'))
+#            utf8_records = []
+#            for row in records:
+#                utf8_row = []
+#                for cell in row:
+#                    encoded_str = cell.encode(self.db_encoding, 'xmlcharrefreplace')
+#                    utf8_row.append(encoded_str.decode('utf-8', 'replace'))
+#                utf8_records.append(utf8_row)
+#            return utf8_columns, utf8_records
+#        else:
+#            return columns, records
 
-

File clearquest/sphinxcontrib/clearquest/directive.py

View file
 # Copyright (c) 2009 by the contributors (see AUTHORS file).
 # All rights reserved.
-# 
+#
 # Redistribution and use in source and binary forms, with or without
 # modification, are permitted provided that the following conditions are
 # met:
-# 
+#
 # * Redistributions of source code must retain the above copyright
 #   notice, this list of conditions and the following disclaimer.
-# 
+#
 # * Redistributions in binary form must reproduce the above copyright
 #   notice, this list of conditions and the following disclaimer in the
 #   documentation and/or other materials provided with the distribution.
-# 
+#
 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
         settings = frontend.OptionParser().get_default_values()
         settings.report_level = 1
         Reporter.__init__(
-            self, 
-            source='sphinxcontrib.clearquest', 
-            report_level=settings.report_level, 
-            halt_level=settings.halt_level, 
-            stream=settings.warning_stream, 
-            debug=settings.debug, 
-            encoding=settings.error_encoding, 
+            self,
+            source='sphinxcontrib.clearquest',
+            report_level=settings.report_level,
+            halt_level=settings.halt_level,
+            stream=settings.warning_stream,
+            debug=settings.debug,
+            encoding=settings.error_encoding,
             error_handler=settings.error_encoding_error_handler
         )
 
 #------------------------------------------------------------------------------
 class ClearQuest(Table):
     """
-    
-    
-    
-    
+    .. clearquest:: directive
     """
-    
+
     option_spec = {
         'username': directives.unchanged,
         'password': directives.unchanged,
         'db_name': directives.unchanged,
         'db_set': directives.unchanged,
-        'params': directives.unchanged
+        'params': directives.unchanged,
     }
 
     required_arguments = 1
     optional_arguments = 0
     final_argument_whitespace = True
     has_content = False
-    
+
     reporter = CQReporter()
-    
+
     connection = None
-    
+
     def run(self):
         try:
             self.resolve_substitutions_refs()
             queryName = self.arguments[0]
             queryParams = self.extract_query_params()
-            
+
             if ClearQuest.connection is None:
-                creds = self.get_credentials()
-                if None in creds.values():
-                    missing = [ name for name, value in creds.items() if value is None ]
+                settings = self.get_settings()
+                if None in settings.values():
+                    missing = [ name for name, value in settings.items() if value is None ]
                     ClearQuest.reporter.warning(console.red( #@UndefinedVariable
-                        'Missing credentials "%s". ' % '", "'.join(missing) + 
-                        'Looked in ~/.sphinxcontrib and in directive options.' 
+                        'Missing settings "%s". ' % '", "'.join(missing) +
+                        'Looked in ~/.sphinxcontrib and in directive options.'
                     ))
                 ClearQuest.reporter.info('Opening ClearQuest session...')
-                ClearQuest.connection = ClearQuestConnection(**creds) 
-            
+                ClearQuest.connection = ClearQuestConnection(**settings)
+
             ClearQuest.reporter.info('Executing ClearQuest query "%s"...' % queryName)
             columns, records = ClearQuest.connection.run_query(queryName, queryParams)
-            
+
             col_widths = self.get_column_widths(header=columns, content=records)
             table_head = [ self.create_row(columns) ]
             table_body = [ self.create_row(line) for line in records ]
-        
+
         except Exception, detail:
             if isinstance(detail, DirectiveError):
                 message = detail.msg
             else:
                 message = str(detail)
             error = ClearQuest.reporter.error(
-                'Error with query data in "%s" directive:\n%s' % (self.name, message), 
-                nodes.literal_block(self.block_text, self.block_text), 
+                'Error with query data in "%s" directive:\n%s' % (self.name, message),
+                nodes.literal_block(self.block_text, self.block_text),
                 line=self.lineno
             )
             return [error]
-        
+
         table = (col_widths, table_head, table_body)
         table_node = self.state.build_table(table, self.content_offset)
         table_node['classes'] += self.options.get('class', [])
-        
+
         return [table_node]
 
     def create_row(self, line):
 
     def get_column_widths(self, header, content):
         widths = [0] * len(header)
-        
+
         for i in range(len(header)):
-            if len(header[i]) > widths[i]:
+            if header[i] is not None and len(header[i]) > widths[i]:
                 widths[i] = len(header[i])
-                
+
         for row in content:
             for i in range(len(row)):
-                if len(row[i]) > widths[i]:
+                if row[i] is not None and len(row[i]) > widths[i]:
                     widths[i] = len(row[i])
-                    
+
         return widths
 
     def extract_query_params(self):
     def resolve_substitutions_refs(self):
         def _subst_ref_match(match):
             return self.state.document.substitution_defs[match.group(1)].astext()
-        
+
         for opt_name in self.options.keys():
             opt_val = unicode(self.options[opt_name])
             opt_val, _ = SUBST_REF_REX.subn(_subst_ref_match, opt_val)
             self.options[opt_name] = opt_val
 
 
-    def get_credentials(self):
-        creds = {
+    def get_settings(self):
+        settings = {
             'username': None,
             'password': None,
             'db_name': None,
             'db_set': None,
         }
-        # first, we try to read connection credentials from ~/.sphinxcontrib 
+        # first, we try to read settings from ~/.sphinxcontrib
         config = ConfigParser.RawConfigParser()
         config.read(path.normpath(path.expanduser('~/.sphinxcontrib')))
         if config.has_section('clearquest'):
-            for name in creds.keys():
+            for name in settings.keys():
                 if config.has_option('clearquest', name):
-                    creds[name] = config.get('clearquest', name)
-        
-        # then, we override the credentials if they are given in the directive
-        for name in creds.keys():
+                    settings[name] = config.get('clearquest', name)
+
+        # then, we override the settings if they are given in the directive
+        for name in settings.keys():
             if self.options.has_key(name) and self.options[name] is not None:
-                creds[name] = self.options[name]
-        
-        return creds
+                settings[name] = self.options[name]
 
+        return settings
 
 
-        
+