changeset 1320:a36c70e5f0dd

Reworked i18n and logging support, from now on, the log is attached to the job page.
author Alexander Schremmer <alex AT alexanderweb DOT de>
date Thu, 17 Aug 2006 21:05:23 +0200
parents c4f6af5ee295
children d0c171c168a8
files MoinMoin/action/SyncPages.py MoinMoin/macro/GetText2.py MoinMoin/mail/mailimport.py MoinMoin/xmlrpc/__init__.py docs/CHANGES.aschremmer
diffstat 5 files changed, 75 insertions(+), 20 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/action/SyncPages.py	Thu Aug 17 19:58:52 2006 +0200
+++ b/MoinMoin/action/SyncPages.py	Thu Aug 17 21:05:23 2006 +0200
@@ -37,19 +37,32 @@
 class ActionStatus(Exception): pass
 
 
-class ActionClass:
-    INFO, WARN, ERROR = range(3) # used for logging
+class ActionClass(object):
+    INFO, WARN, ERROR = zip(range(3), ("", "<!>", "/!\\")) # used for logging
 
     def __init__(self, pagename, request):
         self.request = request
         self.pagename = pagename
-        self.page = Page(request, pagename)
+        self.page = PageEditor(request, pagename)
         self.status = []
         request.flush()
 
-    def log_status(self, level, message):
+    def log_status(self, level, message, substitutions=(), raw_suffix=""):
         """ Appends the message with a given importance level to the internal log. """
-        self.status.append((level, message))
+        self.status.append((level, message, substitutions, raw_suffix))
+
+    def generate_log_table(self):
+        """ Transforms self.status into a user readable table. """
+        table_line = u"|| %(smiley)s || %(message)s%(raw_suffix)s ||"
+        table = []
+
+        for line in self.status:
+            macro_args = [line[1]] + list(line[2])
+            table.append(table_line % {"smiley": line[0][1], "message":
+                u"[[GetText2(|%s)]]" % (packLine(macro_args), ),
+                "raw_suffix": line[3]})
+
+        return "\n".join(table)
 
     def parse_page(self):
         """ Parses the parameter page and returns the read arguments. """
@@ -102,6 +115,7 @@
 
         params = self.fix_params(self.parse_page())
 
+        # XXX aquire readlock on self.page
         try:
             if params["direction"] == UP:
                 raise ActionStatus(_("The only supported directions are BOTH and DOWN."))
@@ -123,11 +137,13 @@
 
             self.sync(params, local, remote)
         except ActionStatus, e:
-            msg = u'<p class="error">%s</p><p>%s</p>\n' % (e.args[0], repr(self.status))
+            msg = u'<p class="error">%s</p><p>%s</p>\n' % (e.args[0], repr(self.status)) # XXX remove self.status
         else:
-            msg = u"%s<p>%s</p>" % (_("Syncronisation finished."), repr(self.status))
+            msg = u"%s<p>%s</p>" % (_("Syncronisation finished."), repr(self.status)) # XXX remove self.status
 
-        # XXX append self.status to the job page
+        self.page.saveText(self.page.get_raw_body() + "\n\n" + self.generate_log_table(), 0)
+
+        # XXX release readlock on self.page
         return self.page.send_page(self.request, msg=msg)
     
     def sync(self, params, local, remote):
@@ -165,11 +181,14 @@
                 ----------+----------+-------------------------------
                 exists    | exists   | already handled.
         """
-        _ = self.request.getText
+        _ = lambda x: x # we will translate it later
+
         direction = params["direction"]
         local_full_iwid = packLine([local.get_iwid(), local.get_interwiki_name()])
         remote_full_iwid = packLine([remote.get_iwid(), remote.get_interwiki_name()])
 
+        self.log_status(self.INFO, _("Syncronisation started -"), raw_suffix=" [[DateTime(%s)]]" % self.page._get_local_timestamp())
+
         l_pages = local.get_pages()
         r_pages = remote.get_pages(exclude_non_writable=direction != DOWN)
 
@@ -180,11 +199,12 @@
 
         m_pages = [elem.add_missing_pagename(local, remote) for elem in SyncPage.merge(l_pages, r_pages)]
 
-        self.log_status(self.INFO, "Got %i local, %i remote pages, %i merged pages" % (len(l_pages), len(r_pages), len(m_pages))) # XXX remove?
+        self.log_status(self.INFO, _("Got a list of %s local and %s remote pages. This results in %s different pages over-all."),
+                        (str(len(l_pages)), str(len(r_pages)), str(len(m_pages))))
 
         if params["pageMatch"]:
             m_pages = SyncPage.filter(m_pages, params["pageMatch"].match)
-        self.log_status(self.INFO, "After filtering: Got %i merges pages" % (len(m_pages), )) # XXX remove
+            self.log_status(self.INFO, _("After filtering: %s pages"), (str(len(m_pages)), ))
 
         on_both_sides = list(SyncPage.iter_local_and_remote(m_pages))
         remote_but_not_local = list(SyncPage.iter_remote_only(m_pages))
@@ -199,7 +219,7 @@
         # XXX handle deleted pages
         for rp in on_both_sides:
             # XXX add locking, acquire read-lock on rp
-            #print "Processing %r" % rp
+            # XXX print "Processing %r" % rp
 
             local_pagename = rp.local_name
             current_page = PageEditor(self.request, local_pagename) # YYY direct access
@@ -227,20 +247,20 @@
                 if newest_tag.remote_rev == rp.remote_rev and (direction == DOWN or newest_tag.current_rev == current_rev):
                     continue # no changes done, next page
                 if rp.local_mime_type != MIMETYPE_MOIN and not (newest_tag.remote_rev == rp.remote_rev ^ newest_tag.current_rev == current_rev):
-                    self.log_status(ActionClass.WARN, _("The item %(pagename)s cannot be merged but was changed in both wikis. Please delete it in one of both wikis and try again.") % {"pagename": rp.name})
+                    self.log_status(ActionClass.WARN, _("The item %s cannot be merged but was changed in both wikis. Please delete it in one of both wikis and try again."), (rp.name, ))
                     continue
                 if rp.local_mime_type != rp.remote_mime_type:
-                    self.log_status(ActionClass.WARN, _("The item %(pagename)s has different mime types in both wikis and cannot be merged. Please delete it in one of both wikis or unify the mime type, and try again.") % {"pagename": rp.name})
+                    self.log_status(ActionClass.WARN, _("The item %s has different mime types in both wikis and cannot be merged. Please delete it in one of both wikis or unify the mime type, and try again."),(rp.name, ))
                     continue
                 if newest_tag.normalised_name != rp.name:
-                    self.log_status(ActionClass.WARN, _("The item %(pagename)s was renamed locally. This is not implemented yet. Therefore all syncronisation history is lost for this page.") % {"pagename": rp.name}) # XXX implement renames
+                    self.log_status(ActionClass.WARN, _("The item %s was renamed locally. This is not implemented yet. Therefore all syncronisation history is lost for this page."), (rp.name, )) # XXX implement renames
                 else:
                     normalised_name = newest_tag.normalised_name
                     local_rev = newest_tag.current_rev
                     remote_rev = newest_tag.remote_rev
                     old_contents = Page(self.request, local_pagename, rev=newest_tag.current_rev).get_raw_body_str() # YYY direct access
 
-            self.log_status(ActionClass.INFO, _("Synchronising page %(pagename)s with remote page %(remotepagename)s ...") % {"pagename": local_pagename, "remotepagename": rp.remote_name})
+            self.log_status(ActionClass.INFO, _("Synchronising page %s with remote page %s ..."), (local_pagename, rp.remote_name))
 
             if direction == DOWN:
                 remote_rev = None # always fetch the full page, ignore remote conflict check
@@ -251,7 +271,7 @@
             if remote_rev != rp.remote_rev:
                 diff_result = remote.get_diff(rp.remote_name, remote_rev, None, normalised_name)
                 if diff_result is None:
-                    self.log_status(ActionClass.ERROR, _("The page %(pagename)s could not be synced. The remote page was renamed. This is not supported yet. You may want to delete one of the pages to get it synced.") % {"pagename": rp.remote_name})
+                    self.log_status(ActionClass.ERROR, _("The page %s could not be synced. The remote page was renamed. This is not supported yet. You may want to delete one of the pages to get it synced."), (rp.remote_name, ))
                     continue
                 is_remote_conflict = diff_result["conflict"]
                 assert diff_result["diffversion"] == 1
@@ -269,7 +289,7 @@
             # and the page has never been syncronised
             if (rp.local_mime_type == MIMETYPE_MOIN and wikiutil.containsConflictMarker(current_page.get_raw_body())
                 and (remote_rev is None or is_remote_conflict)):
-                self.log_status(ActionClass.WARN, _("Skipped page %(pagename)s because of a locally or remotely unresolved conflict.") % {"pagename": local_pagename})
+                self.log_status(ActionClass.WARN, _("Skipped page %s because of a locally or remotely unresolved conflict."), (local_pagename, ))
                 continue
 
             if remote_rev is None and direction == BOTH:
@@ -293,7 +313,7 @@
                     verynewtext_raw = current_page.get_raw_body_str()
 
             diff = textdiff(new_contents, verynewtext_raw)
-            #print "Diff against %r" % new_contents.encode("utf-8")
+            # XXX print "Diff against %r" % new_contents.encode("utf-8")
 
             comment = u"Local Merge - %r" % (remote.get_interwiki_name() or remote.get_iwid())
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MoinMoin/macro/GetText2.py	Thu Aug 17 21:05:23 2006 +0200
@@ -0,0 +1,29 @@
+# -*- coding: iso-8859-1 -*-
+"""
+    MoinMoin - Load I18N Text and substitute data.
+
+    This macro has the main purpose of being used by extensions that write
+    data to wiki pages but want to ensure that it is properly translated.
+
+    @copyright: 2006 by MoinMoin:AlexanderSchremmer
+    @license: GNU GPL, see COPYING for details.
+"""
+
+from MoinMoin import wikiutil
+from MoinMoin.packages import unpackLine
+
+Dependencies = ["language"]
+
+def execute(macro, args):
+    """ args consists of a character specifiying the separator and then a
+    packLine sequence describing a list. The first element of it is the message
+    and the remaining elements are substituted in the message using string
+    substitution.
+    """
+    sep = args[0]
+    args = unpackLine(args[1:], sep)
+    translation = macro.request.getText(args[0], formatted=False)
+    message = translation % tuple(args[1:])
+
+    return macro.formatter.text(message)
+
--- a/MoinMoin/mail/mailimport.py	Thu Aug 17 19:58:52 2006 +0200
+++ b/MoinMoin/mail/mailimport.py	Thu Aug 17 21:05:23 2006 +0200
@@ -269,6 +269,10 @@
             elif table_ends is not None and not line.startswith("||"):
                 break
 
+        # in order to let the gettext system recognise the [[GetText]] calls used below,
+        # we must repeat them here:
+        [_("From"), _("To"), _("Content"), _("Date"), _("Attachments")]
+
         table_header = (u"\n\n## mail_overview (don't delete this line)\n" +
                         u"|| '''[[GetText(From)]] ''' || '''[[GetText(To)]] ''' || '''[[GetText(Content)]] ''' || '''[[GetText(Date)]] ''' || '''[[GetText(Attachments)]] ''' ||\n"
                        )
--- a/MoinMoin/xmlrpc/__init__.py	Thu Aug 17 19:58:52 2006 +0200
+++ b/MoinMoin/xmlrpc/__init__.py	Thu Aug 17 21:05:23 2006 +0200
@@ -706,11 +706,12 @@
         """
         from MoinMoin.util.bdiff import decompress, patch
         from MoinMoin.wikisync import TagStore, BOTH
+        from MoinMoin.packages import unpackLine
         LASTREV_INVALID = xmlrpclib.Fault("LASTREV_INVALID", "The page was changed")
 
         pagename = self._instr(pagename)
 
-        comment = u"Remote Merge - %r" % interwiki_name
+        comment = u"Remote Merge - %r" % unpackLine(interwiki_name)[-1]
         
         # User may read page?
         if not self.request.user.may.read(pagename) or not self.request.user.may.write(pagename):
--- a/docs/CHANGES.aschremmer	Thu Aug 17 19:58:52 2006 +0200
+++ b/docs/CHANGES.aschremmer	Thu Aug 17 21:05:23 2006 +0200
@@ -114,6 +114,7 @@
          normalised name. Implemented preliminary mime type support, only transmission of the mime type
          and the new storage API is missing. Changed getDiff interface. Detect renamed pages (and choke :).
          Added infrastructure support for detecting deleted pages (not used in the merging logic yet).
+         Reworked i18n and logging support.
 
 2006-07-18: the requested daily entry is missing here, see http://moinmoin.wikiwikiweb.de/GoogleSoc2006/BetterProgress
 2006-07-19: the requested daily entry is missing here, see http://moinmoin.wikiwikiweb.de/GoogleSoc2006/BetterProgress