jenkins-bot has submitted this change and it was merged.
Change subject: Deprecate BaseSite.*_namespace() ......................................................................
Deprecate BaseSite.*_namespace()
Add NamespacesDict.builtin_namespaces() and key lookup by string.
Change-Id: I2fde4d6e755f227ef20f345ee74be8fc0eff5b16 --- M pywikibot/page.py M pywikibot/site.py M pywikibot/textlib.py M scripts/catall.py M scripts/image.py M scripts/imagetransfer.py M scripts/makecat.py M scripts/noreferences.py M scripts/templatecount.py M tests/namespace_tests.py 10 files changed, 139 insertions(+), 16 deletions(-)
Approvals: XZise: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py index 890796a..45110ef 100644 --- a/pywikibot/page.py +++ b/pywikibot/page.py @@ -2528,7 +2528,7 @@ # move to category.py? (Although it doesn't seem to be used there, # either) if not isinstance(cat, Category): - cat = self.site.category_namespace() + ':' + cat + cat = self.site.namespaces.CATEGORY + ':' + cat targetCat = Category(self.site, cat) else: targetCat = cat @@ -2569,7 +2569,7 @@ """ # I don't see why we need this as part of the framework either # move to scripts/category.py? - catname = self.site.category_namespace() + ':' + catname + catname = self.site.namespaces.CATEGORY + ':' + catname targetCat = Category(self.site, catname) if targetCat.exists(): pywikibot.warning(u'Target page %s already exists!' diff --git a/pywikibot/site.py b/pywikibot/site.py index 3f3fe9f..c4b28eb 100644 --- a/pywikibot/site.py +++ b/pywikibot/site.py @@ -152,6 +152,25 @@ properties will have the same value. """
+ MEDIA = -2 + SPECIAL = -1 + MAIN = 0 + TALK = 1 + USER = 2 + USER_TALK = 3 + PROJECT = 4 + PROJECT_TALK = 5 + FILE = 6 + FILE_TALK = 7 + MEDIAWIKI = 8 + MEDIAWIKI_TALK = 9 + TEMPLATE = 10 + TEMPLATE_TALK = 11 + HELP = 12 + HELP_TALK = 13 + CATEGORY = 14 + CATEGORY_TALK = 15 + # These are the MediaWiki built-in names for MW 1.14+. # Namespace prefixes are always case-insensitive, but the # canonical forms are capitalized. @@ -478,9 +497,41 @@ """Iterate over all namespaces.""" return iter(self._namespaces)
- def __getitem__(self, number): - """Get the namespace with the given number.""" - return self._namespaces[number] + def __getitem__(self, key): + """ + Get the namespace with the given key. + + @param key: namespace key + @type key: Namespace, int or str + @rtype: Namespace + """ + if isinstance(key, (Namespace, int)): + return self._namespaces[key] + else: + namespace = self.lookup_name(key) + if namespace: + return namespace + + return super(NamespacesDict, self).__getitem__(key) + + def __getattr__(self, attr): + """ + Get the namespace with the given key. + + @param key: namespace key + @type key: Namespace, int or str + @rtype: Namespace + """ + # lookup_name access _namespaces + if attr.isupper(): + if attr == 'MAIN': + return self[0] + + namespace = self.lookup_name(attr) + if namespace: + return namespace + + return self.__getattribute__(attr)
def __len__(self): """Get the number of namespaces.""" @@ -1035,26 +1086,32 @@
# namespace shortcuts for backwards-compatibility
+ @deprecated('namespaces.SPECIAL') def special_namespace(self): """Return local name for the Special: namespace.""" return self.namespace(-1)
+ @deprecated('namespaces.FILE') def image_namespace(self): """Return local name for the File namespace.""" return self.namespace(6)
+ @deprecated('namespaces.MEDIAWIKI') def mediawiki_namespace(self): """Return local name for the MediaWiki namespace.""" return self.namespace(8)
+ @deprecated('namespaces.TEMPLATE') def template_namespace(self): """Return local name for the Template namespace.""" return self.namespace(10)
+ @deprecated('namespaces.CATEGORY') def category_namespace(self): """Return local name for the Category namespace.""" return self.namespace(14)
+ @deprecated('list(namespaces.CATEGORY)') def category_namespaces(self): """Return names for the Category namespace.""" return self.namespace(14, all=True) diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py index bd7adbd..7cefc3d 100644 --- a/pywikibot/textlib.py +++ b/pywikibot/textlib.py @@ -993,7 +993,7 @@ # Ignore category links within nowiki tags, pre tags, includeonly tags, # and HTML comments text = removeDisabledParts(text, include=include) - catNamespace = '|'.join(site.category_namespaces()) + catNamespace = '|'.join(site.namespaces.CATEGORY) R = re.compile(r'[[\s*(?P<namespace>%s)\s*:\s*(?P<rest>.+?)]]' % catNamespace, re.I) for match in R.finditer(text): @@ -1025,7 +1025,7 @@ # ASCII letters and hyphens. if site is None: site = pywikibot.Site() - catNamespace = '|'.join(site.category_namespaces()) + catNamespace = '|'.join(site.namespaces.CATEGORY) categoryR = re.compile(r'[[\s*(%s)\s*:.*?]]\s*' % catNamespace, re.I) text = replaceExcept(text, categoryR, '', ['nowiki', 'comment', 'math', 'pre', 'source', 'includeonly'], @@ -1070,7 +1070,7 @@ if site is None: site = pywikibot.Site()
- catNamespace = '|'.join(site.category_namespaces()) + catNamespace = '|'.join(site.namespaces.CATEGORY) title = oldcat.title(withNamespace=False) if not title: return diff --git a/scripts/catall.py b/scripts/catall.py index f2042ef..0e525f9 100755 --- a/scripts/catall.py +++ b/scripts/catall.py @@ -75,7 +75,7 @@ site = pywikibot.Site() pllist = [] for p in list: - cattitle = "%s:%s" % (site.category_namespace(), p) + cattitle = "%s:%s" % (site.namespaces.CATEGORY, p) pllist.append(pywikibot.Page(site, cattitle)) page.put_async(textlib.replaceCategoryLinks(page.get(), pllist, site=page.site), diff --git a/scripts/image.py b/scripts/image.py index de8cd3b..f780856 100755 --- a/scripts/image.py +++ b/scripts/image.py @@ -160,7 +160,7 @@ if not self.getOption('loose'): replacements.append((image_regex, u'[[%s:%s\g<parameters>]]' - % (self.site.image_namespace(), + % (self.site.namespaces.FILE, self.new_image))) else: replacements.append((image_regex, self.new_image)) diff --git a/scripts/imagetransfer.py b/scripts/imagetransfer.py index 700de25..670c809 100755 --- a/scripts/imagetransfer.py +++ b/scripts/imagetransfer.py @@ -246,7 +246,7 @@ # to upload anyway, using another name. try: # Maybe the image is on the target site already - targetTitle = '%s:%s' % (self.targetSite.image_namespace(), + targetTitle = '%s:%s' % (self.targetSite.namespaces.FILE, image.title().split(':', 1)[1]) targetImage = pywikibot.Page(self.targetSite, targetTitle) targetImage.get() diff --git a/scripts/makecat.py b/scripts/makecat.py index 88d8ce0..bf158ff 100755 --- a/scripts/makecat.py +++ b/scripts/makecat.py @@ -211,7 +211,7 @@ pywikibot.setAction(i18n.twtranslate(mysite, 'makecat-create', {'cat': workingcatname})) workingcat = pywikibot.Category(mysite, u'%s:%s' - % (mysite.category_namespace(), + % (mysite.namespaces.CATEGORY, workingcatname)) filename = pywikibot.config.datafilepath( 'category', workingcatname.encode('ascii', 'xmlcharrefreplace') + '_exclude.txt') diff --git a/scripts/noreferences.py b/scripts/noreferences.py index df65e8c..cc603e6 100755 --- a/scripts/noreferences.py +++ b/scripts/noreferences.py @@ -608,7 +608,7 @@ # keep removing interwiki links, templates etc. from the bottom. # At the end, look at the length of the temp text. That's the position # where we'll insert the references section. - catNamespaces = '|'.join(self.site.category_namespaces()) + catNamespaces = '|'.join(self.site.namespaces.CATEGORY) categoryPattern = r'[[\s*(%s)\s*:[^\n]*]]\s*' % catNamespaces interwikiPattern = r'[[([a-zA-Z-]+)\s?:([^[]\n]*)]]\s*' # won't work with nested templates @@ -730,7 +730,7 @@ pass else: cat = pywikibot.Category(site, "%s:%s" % ( - site.category_namespace(), cat)) + site.namespaces.CATEGORY, cat)) gen = cat.articles(namespaces=genFactory.namespaces or [0]) if gen: bot = NoReferencesBot(gen, **options) diff --git a/scripts/templatecount.py b/scripts/templatecount.py index a4f9585..5e9bc34 100755 --- a/scripts/templatecount.py +++ b/scripts/templatecount.py @@ -98,7 +98,7 @@ mysite = pywikibot.Site() # The names of the templates are the keys, and lists of pages # transcluding templates are the values. - mytpl = mysite.namespaces.lookup_name(mysite.template_namespace()) + mytpl = mysite.namespaces.TEMPLATE for template in templates: transcludingArray = [] gen = pywikibot.Page(mysite, template, ns=mytpl).getReferences( diff --git a/tests/namespace_tests.py b/tests/namespace_tests.py index 024ba7f..9d9c6a6 100644 --- a/tests/namespace_tests.py +++ b/tests/namespace_tests.py @@ -10,7 +10,7 @@ __version__ = '$Id$'
from collections import Iterable -from pywikibot.site import Namespace +from pywikibot.site import Namespace, NamespacesDict from tests.aspects import unittest, TestCase, AutoDeprecationTestCase
import sys @@ -44,6 +44,11 @@ file_builtin_ns['File'] = 6 file_builtin_ns['File talk'] = 7 builtin_ns = dict(list(image_builtin_ns.items()) + list(file_builtin_ns.items())) + + +def builtin_NamespacesDict(): + """Return a NamespacesDict of the builtin namespaces.""" + return NamespacesDict(Namespace.builtin_namespaces())
class TestNamespaceObject(TestCase): @@ -331,6 +336,67 @@ len(positive_namespaces) + len(excluded_namespaces))
+class TestNamespacesDictGetItem(TestCase): + + """Test NamespacesDict.__getitem__.""" + + net = False + + def test_ids(self): + """Test lookup by canonical namespace id.""" + namespaces = builtin_NamespacesDict() + for namespace in namespaces.values(): + self.assertEqual(namespace, namespaces[namespace.id]) + + def test_namespace(self): + """Test lookup by Namespace object.""" + namespaces = builtin_NamespacesDict() + for namespace in namespaces.values(): + self.assertEqual(namespace, namespaces[namespace]) + + def test_invalid_id(self): + """Test lookup by invalid id.""" + namespaces = builtin_NamespacesDict() + lower = min(namespaces.keys()) - 1 + higher = max(namespaces.keys()) + 1 + self.assertRaises(KeyError, namespaces.__getitem__, lower) + self.assertRaises(KeyError, namespaces.__getitem__, higher) + + def test_canonical_name(self): + """Test lookup by canonical namespace name.""" + namespaces = builtin_NamespacesDict() + for namespace in namespaces.values(): + self.assertEqual(namespace, namespaces[namespace.canonical_name]) + self.assertEqual(namespace, + namespaces[namespace.canonical_name.upper()]) + + def test_canonical_attr(self): + """Test attribute lookup by canonical namespace name.""" + namespaces = builtin_NamespacesDict() + self.assertEqual(namespaces[0], namespaces.MAIN) + self.assertEqual(namespaces[1], namespaces.TALK) + + for namespace in namespaces.values(): + if namespace.id == 0: + continue + attr = namespace.canonical_name.upper() + self.assertEqual(namespace, getattr(namespaces, attr)) + + def test_all(self): + """Test lookup by any namespace name.""" + namespaces = builtin_NamespacesDict() + for namespace in namespaces.values(): + for name in namespace: + self.assertEqual(namespace, namespaces[name.upper()]) + + def test_invalid_name(self): + """Test lookup by invalid name.""" + namespaces = builtin_NamespacesDict() + self.assertRaises(KeyError, namespaces.__getitem__, 'FOO') + # '|' is not permitted in namespace names + self.assertRaises(KeyError, namespaces.__getitem__, '|') + + if __name__ == '__main__': try: unittest.main()
pywikibot-commits@lists.wikimedia.org