Xqt has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/263183

Change subject: Move listpages.Formatter class to pywikibot.tools.formatter.py
......................................................................

Move listpages.Formatter class to pywikibot.tools.formatter.py

- move script Formatter class to tools library. This enables to reuse it
  e.g. for templatescount script later.
- add some tests to tools_formatter_tests

Also made bugfixes for Formatter.output method:
- fmt default parameter must be a string, not a integer
- use '3' as default option.
  Otherwise the method fails if num parameter isn't set.

Change-Id: Ie7dcdd45b3c339ab23b00cf04e44608b057fb33f
---
M pywikibot/tools/formatter.py
M scripts/listpages.py
M tests/tools_formatter_tests.py
3 files changed, 89 insertions(+), 68 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/83/263183/1

diff --git a/pywikibot/tools/formatter.py b/pywikibot/tools/formatter.py
index a571ee4..939bcd1 100644
--- a/pywikibot/tools/formatter.py
+++ b/pywikibot/tools/formatter.py
@@ -1,7 +1,7 @@
 # -*- coding: utf-8  -*-
 """Module containing various formatting related utilities."""
 #
-# (C) Pywikibot team, 2015
+# (C) Pywikibot team, 2015-2016
 #
 # Distributed under the terms of the MIT license.
 #
@@ -63,6 +63,70 @@
         output(self.format_list())
 
 
+class PagelistFormatter(object):
+
+    """Structure with Page attributes exposed for formatting from cmd line."""
+
+    fmt_options = {
+        '1': u"{num:4d} {page.title}",
+        '2': u"{num:4d} [[{page.title}]]",
+        '3': u"{page.title}",
+        '4': u"[[{page.title}]]",
+        '5': u"{num:4d} \03{{lightred}}{page.loc_title:<40}\03{{default}}",
+        '6': u"{num:4d} {page.loc_title:<40} {page.can_title:<40}",
+        '7': u"{num:4d} {page.loc_title:<40} {page.trs_title:<40}",
+    }
+
+    # Identify which formats need outputlang
+    fmt_need_lang = [k for k, v in fmt_options.items() if 'trs_title' in v]
+
+    def __init__(self, page, outputlang=None, default='******'):
+        """
+        Constructor.
+
+        @param page: the page to be formatted.
+        @type page: Page object.
+        @param outputlang: language code in which namespace before title should
+            be translated.
+
+            Page ns will be searched in Site(outputlang, page.site.family)
+            and, if found, its custom name will be used in page.title().
+
+        @type outputlang: str or None, if no translation is wanted.
+        @param default: default string to be used if no corresponding
+            namespace is found when outputlang is not None.
+
+        """
+        self.site = page._link.site
+        self.title = page._link.title
+        self.loc_title = page._link.canonical_title()
+        self.can_title = page._link.ns_title()
+        self.outputlang = outputlang
+        if outputlang is not None:
+            # Cache onsite in case of translations.
+            if not hasattr(self, "onsite"):
+                self.onsite = pywikibot.Site(outputlang, self.site.family)
+            try:
+                self.trs_title = page._link.ns_title(onsite=self.onsite)
+            # Fallback if no corresponding namespace is found in onsite.
+            except pywikibot.Error:
+                self.trs_title = u'%s:%s' % (default, page._link.title)
+
+    def output(self, num=None, fmt='3'):
+        """Output formatted string."""
+        fmt = self.fmt_options.get(fmt, fmt)
+        # If selected format requires trs_title, outputlang must be set.
+        if (fmt in self.fmt_need_lang or
+                'trs_title' in fmt and
+                self.outputlang is None):
+            raise ValueError(
+                u"Required format code needs 'outputlang' parameter set.")
+        if num is None:
+            return fmt.format(page=self)
+        else:
+            return fmt.format(num=num, page=self)
+
+
 class _ColorFormatter(Formatter):
 
     """Special string formatter which skips colors."""
diff --git a/scripts/listpages.py b/scripts/listpages.py
index 8c3c8f7..4f35ba6 100755
--- a/scripts/listpages.py
+++ b/scripts/listpages.py
@@ -83,7 +83,7 @@
 &params;
 """
 #
-# (C) Pywikibot team, 2008-2014
+# (C) Pywikibot team, 2008-2016
 #
 # Distributed under the terms of the MIT license.
 #
@@ -98,72 +98,9 @@
 import pywikibot
 from pywikibot import config2 as config, i18n
 from pywikibot.pagegenerators import GeneratorFactory, parameterHelp
+from pywikibot.tools.formatter import PagelistFormatter
 
 docuReplacements = {'&params;': parameterHelp}
-
-
-class Formatter(object):
-
-    """Structure with Page attributes exposed for formatting from cmd line."""
-
-    fmt_options = {
-        '1': u"{num:4d} {page.title}",
-        '2': u"{num:4d} [[{page.title}]]",
-        '3': u"{page.title}",
-        '4': u"[[{page.title}]]",
-        '5': u"{num:4d} \03{{lightred}}{page.loc_title:<40}\03{{default}}",
-        '6': u"{num:4d} {page.loc_title:<40} {page.can_title:<40}",
-        '7': u"{num:4d} {page.loc_title:<40} {page.trs_title:<40}",
-    }
-
-    # Identify which formats need outputlang
-    fmt_need_lang = [k for k, v in fmt_options.items() if 'trs_title' in v]
-
-    def __init__(self, page, outputlang=None, default='******'):
-        """
-        Constructor.
-
-        @param page: the page to be formatted.
-        @type page: Page object.
-        @param outputlang: language code in which namespace before title should
-            be translated.
-
-            Page ns will be searched in Site(outputlang, page.site.family)
-            and, if found, its custom name will be used in page.title().
-
-        @type outputlang: str or None, if no translation is wanted.
-        @param default: default string to be used if no corresponding
-            namespace is found when outputlang is not None.
-
-        """
-        self.site = page._link.site
-        self.title = page._link.title
-        self.loc_title = page._link.canonical_title()
-        self.can_title = page._link.ns_title()
-        self.outputlang = outputlang
-        if outputlang is not None:
-            # Cache onsite in case of translations.
-            if not hasattr(self, "onsite"):
-                self.onsite = pywikibot.Site(outputlang, self.site.family)
-            try:
-                self.trs_title = page._link.ns_title(onsite=self.onsite)
-            # Fallback if no corresponding namespace is found in onsite.
-            except pywikibot.Error:
-                self.trs_title = u'%s:%s' % (default, page._link.title)
-
-    def output(self, num=None, fmt=1):
-        """Output formatted string."""
-        fmt = self.fmt_options.get(fmt, fmt)
-        # If selected format requires trs_title, outputlang must be set.
-        if (fmt in self.fmt_need_lang or
-                'trs_title' in fmt and
-                self.outputlang is None):
-            raise ValueError(
-                u"Required format code needs 'outputlang' parameter set.")
-        if num is None:
-            return fmt.format(page=self)
-        else:
-            return fmt.format(num=num, page=self)
 
 
 def main(*args):
@@ -250,7 +187,7 @@
         output_list = []
         for i, page in enumerate(gen, start=1):
             if not notitle:
-                page_fmt = Formatter(page, outputlang)
+                page_fmt = PagelistFormatter(page, outputlang)
                 output_list += [page_fmt.output(num=i, fmt=fmt)]
                 pywikibot.stdout(output_list[-1])
             if page_get:
diff --git a/tests/tools_formatter_tests.py b/tests/tools_formatter_tests.py
index eb1a84b..46db9be 100644
--- a/tests/tools_formatter_tests.py
+++ b/tests/tools_formatter_tests.py
@@ -1,7 +1,7 @@
 # -*- coding: utf-8  -*-
 """Tests for the C{pywikibot.tools.formatter} module."""
 #
-# (C) Pywikibot team, 2015
+# (C) Pywikibot team, 2015-2016
 #
 # Distributed under the terms of the MIT license.
 #
@@ -9,6 +9,7 @@
 
 __version__ = '$Id$'
 #
+import pywikibot
 from pywikibot.tools import formatter
 from pywikibot.tools import UnicodeMixin
 
@@ -19,6 +20,8 @@
 
     """Test ListFormatter class."""
 
+    family = 'wikipedia'
+    code = 'en'
     net = False
 
     def test_SequenceOutputter(self):
@@ -31,6 +34,23 @@
         outputter.format_string = '{item}'
         self.assertEqual(outputter.format_list(), '\nfoo\nbar\n')
 
+    def test_PagelistFormatter(self):
+        """Test format method."""
+        site = self.get_site()
+        page = pywikibot.Page(site, 'foo')
+        outputter = formatter.PagelistFormatter(page)
+        self.assertEqual(outputter.output(), 'Foo')
+        self.assertEqual(outputter.output(10, '1'), '  10 Foo')
+        self.assertEqual(outputter.output(11, '2'), '  11 [[Foo]]')
+        self.assertEqual(outputter.output(12, '3'), 'Foo')
+        self.assertEqual(outputter.output(13, '4'), '[[Foo]]')
+        self.assertEqual(outputter.output(14, '5'),
+                         '  14 \x03{lightred}Foo' + ' ' * 37 + '\x03{default}')
+        self.assertEqual(outputter.output(15, '6'),
+                         '  15 Foo' + ' ' * 37 + ' Foo' + ' ' * 37)
+        self.assertEqual(outputter.output(17, '{num} *{{{{{page.title}}}}}*'),
+                         '17 *{{Foo}}*')
+
 
 class TestColorFormat(TestCase):
 

-- 
To view, visit https://gerrit.wikimedia.org/r/263183
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ie7dcdd45b3c339ab23b00cf04e44608b057fb33f
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <[email protected]>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to