changeset 273:3b5e856b3a32

Bridge: added mediawiki constructor in bridge constructor, usefull for documentation purpose
author Goffi <goffi@goffi.org>
date Tue, 25 Jan 2011 01:37:02 +0100
parents 1d2e0dfe7114
children c1ad04586edf
files MANIFEST.in src/bridge/bridge_constructor/bridge_contructor.py
diffstat 2 files changed, 139 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/MANIFEST.in	Mon Jan 24 22:05:04 2011 +0100
+++ b/MANIFEST.in	Tue Jan 25 01:37:02 2011 +0100
@@ -8,4 +8,5 @@
 include src/sat.*
 include frontends/src/jp/jp frontends/src/primitivus/primitivus frontends/src/wix/wix
 include frontends/src/wix/images/cards/.size
+include src/bridge/bridge_constructor/mediawiki_template.tpl
 prune src/bridge/bridge_constructor/generated
--- a/src/bridge/bridge_constructor/bridge_contructor.py	Mon Jan 24 22:05:04 2011 +0100
+++ b/src/bridge/bridge_constructor/bridge_contructor.py	Tue Jan 25 01:37:02 2011 +0100
@@ -35,8 +35,9 @@
 
 This script construct a SàT bridge using the given protocol
 """
-MANAGED_PROTOCOLES=['dbus']
+MANAGED_PROTOCOLES=['dbus','mediawiki']
 DEFAULT_PROTOCOLE='dbus'
+FLAGS=['deprecated']
 
 import sys
 import os
@@ -45,6 +46,7 @@
 from ConfigParser import SafeConfigParser as Parser
 from ConfigParser import NoOptionError
 import re
+from datetime import datetime
 
 
 class ParseError(Exception):
@@ -78,9 +80,6 @@
         def_re = re.compile(r"param_(\d+)_default")
         
         for option in self.bridge_template.options(name):
-            if option == 'doc_return':
-                default_dict['return'] = self.bridge_template.get(name, option)
-                continue
             match = def_re.match(option)
             if match:
                 try:
@@ -91,6 +90,16 @@
         
         return default_dict
 
+    def getFlags(self, name):
+        """Return list of flags set for this function
+        @param name: Name of the function to get
+        @return: List of flags (string)"""
+        flags=[]
+        for option in self.bridge_template.options(name):
+            if option in FLAGS:
+                flags.append(option)
+        return flags
+    
     def getArgumentsDoc(self, name):
         """Return documentation of arguments
         @param name: Name of the function to get
@@ -99,6 +108,9 @@
         option_re = re.compile(r"doc_param_(\d+)")
         value_re = re.compile(r"^(\w+): (.*)$", re.MULTILINE | re.DOTALL)
         for option in self.bridge_template.options(name):
+            if option == 'doc_return':
+                doc_dict['return'] = self.bridge_template.get(name, option)
+                continue
             match = option_re.match(option)
             if match:
                 try:
@@ -110,6 +122,14 @@
                     raise ParseError("Invalid value for parameter doc [%i]" % idx)
                 doc_dict[idx]=(value_match.group(1),value_match.group(2))
         return doc_dict
+
+    def getDoc(self, name):
+        """Return documentation of the method
+        @param name: Name of the function to get
+        @return: string documentation, or None"""
+        if self.bridge_template.has_option(name, "doc"):
+            return self.bridge_template.get(name, "doc")
+        return None
     
     def getArguments(self, signature, name=None, default=None, unicode_protect=False):
         """Return arguments to user given a signature
@@ -184,6 +204,118 @@
             print("It's not possible to generate the file, check your permissions")
             exit(1)
 
+class MediawikiConstructor(Constructor):
+
+    def __init__(self, bridge_template, options):
+        Constructor.__init__(self, bridge_template, options)
+        self.core_template="mediawiki_template.tpl" 
+        self.core_dest="mediawiki.wiki" 
+
+    def _wikiParameter(self, name, sig_in):
+        """Format parameters with the wiki syntax
+        @param name: name of the function
+        @param sig_in: signature in
+        @return: string of the formated parameters"""
+        arg_doc = self.getArgumentsDoc(name)
+        arg_default = self.getDefault(name)
+        args_str = self.getArguments(sig_in)
+        args = args_str.split(', ') if args_str else [] #ugly but it works :)
+        wiki=[]
+        for i in range(len(args)):
+            if arg_doc.has_key(i):
+                name,doc=arg_doc[i]
+                doc='\n:'.join(doc.rstrip('\n').split('\n'))
+                wiki.append("; %s: %s" % (name, doc))
+            else:
+                wiki.append("; arg_%d: " % i)
+            if arg_default.has_key(i):
+                wiki.append(":''DEFAULT: %s''" % arg_default[i])
+        return "\n".join(wiki)
+         
+    def _wikiReturn(self, name):
+        """Format return doc with the wiki syntax
+        @param name: name of the function
+        """
+        arg_doc = self.getArgumentsDoc(name)
+        wiki=[]
+        if arg_doc.has_key('return'):
+            wiki.append('\n|-\n! scope=row | return value\n|')
+            wiki.append('<br />\n'.join(arg_doc['return'].rstrip('\n').split('\n')))
+        return "\n".join(wiki)
+
+    def generateCoreSide(self):
+        signals_part = []
+        methods_part = []
+        sections = self.bridge_template.sections()
+        sections.sort()
+        for section in sections:
+            function = self.getValues(section)
+            print ("Adding %s %s" % (section, function["type"]))
+            default = self.getDefault(section)
+            deprecated_msg = """<br />'''<font color="#FF0000">/!\ WARNING /!\ : This method is deprecated, please don't use it !</font>'''"""
+            signature_signal = \
+"""\
+! scope=row | signature
+| %s
+|-\
+""" % function['sig_in']
+            signature_method = \
+"""\
+! scope=row | signature in
+| %s
+|-
+! scope=row | signature out
+| %s
+|-\
+""" % (function['sig_in'], function['sig_out'])
+            completion = {
+                'signature':signature_signal if function['type']=="signal" else signature_method,
+                'sig_out':function['sig_out'] or '',
+                'category':function['category'],
+                'name':section,
+                'doc':self.getDoc(section) or "FIXME: No description available",
+                'deprecated':deprecated_msg if "deprecated" in self.getFlags(section) else "",
+                'parameters':self._wikiParameter(section, function['sig_in']),
+                'return':self._wikiReturn(section) if function['type'] == 'method' else ''
+                }
+
+            dest = signals_part if function['type'] == "signal" else methods_part
+            dest.append("""\
+== %(name)s ==
+''%(doc)s''
+%(deprecated)s
+{| class="wikitable" style="text-align:left; width:80%%;"
+! scope=row | category
+| %(category)s 
+|-
+%(signature)s
+! scope=row | parameters
+|
+%(parameters)s%(return)s
+|}
+""" % completion)
+        
+        #at this point, signals_part, and methods_part should be filled,
+        #we just have to place them in the right part of the template
+        core_bridge = []
+        try:
+            with open(self.core_template) as core_template:
+                for line in core_template:
+                    if line.startswith('##SIGNALS_PART##'):
+                        core_bridge.extend(signals_part)
+                    elif line.startswith('##METHODS_PART##'):
+                        core_bridge.extend(methods_part)
+                    elif line.startswith('##TIMESTAMP##'):
+                        core_bridge.append('Generated on %s' % datetime.now())
+                    else:
+                        core_bridge.append(line.replace('\n',''))
+        except IOError:
+            print ("Can't open template file [%s]" % self.core_template)
+            sys.exit(1) 
+
+        #now we write to final file
+        self.finalWrite(self.core_dest, core_bridge)
+
 class DbusConstructor(Constructor):
 
     def __init__(self, bridge_template, options):
@@ -305,6 +437,8 @@
     def create(self, bridge_template, options):
        if options.protocole=='dbus':
            return DbusConstructor(bridge_template, options)
+       elif options.protocole=='mediawiki':
+           return MediawikiConstructor(bridge_template, options)
 
        raise ConstructorError('Unknown constructor type')