[Pywikipedia-l] SVN: [5453] branches/rewrite/pywikibot

russblau at svn.wikimedia.org russblau at svn.wikimedia.org
Wed May 28 13:23:58 UTC 2008


Revision: 5453
Author:   russblau
Date:     2008-05-28 13:23:58 +0000 (Wed, 28 May 2008)

Log Message:
-----------
add site.code property and separate wiki i.d. code from language (which may be different)

Modified Paths:
--------------
    branches/rewrite/pywikibot/date.py
    branches/rewrite/pywikibot/login.py
    branches/rewrite/pywikibot/page.py
    branches/rewrite/pywikibot/site.py

Modified: branches/rewrite/pywikibot/date.py
===================================================================
--- branches/rewrite/pywikibot/date.py	2008-05-28 12:28:34 UTC (rev 5452)
+++ branches/rewrite/pywikibot/date.py	2008-05-28 13:23:58 UTC (rev 5453)
@@ -1500,7 +1500,7 @@
         self.site = site
 
     def __call__(self, m, d):
-        return formats['Day_' + enMonthNames[m-1]][self.site.lang](d)
+        return formats['Day_' + enMonthNames[m-1]][self.site.code](d)
 
 
 def formatYear(lang, year):

Modified: branches/rewrite/pywikibot/login.py
===================================================================
--- branches/rewrite/pywikibot/login.py	2008-05-28 12:28:34 UTC (rev 5452)
+++ branches/rewrite/pywikibot/login.py	2008-05-28 13:23:58 UTC (rev 5453)
@@ -72,24 +72,24 @@
         if sysop:
             try:
                 self.username = config.sysopnames\
-                                [self.site.family.name][self.site.language()]
+                                [self.site.family.name][self.site.code]
             except:
                 raise NoUsername(
 u'ERROR: Sysop username for %s:%s is undefined.\nIf you have a sysop account for that site, please add such a line to user-config.py:\n\nsysopnames[\'%s\'][\'%s\'] = \'myUsername\''
-                      % (self.site.family.name, self.site.language(),
-                         self.site.family.name, self.site.language()))
+                      % (self.site.family.name, self.site.code,
+                         self.site.family.name, self.site.code))
         else:
             try:
                 self.username = config.usernames\
-                                [self.site.family.name][self.site.language()]
+                                [self.site.family.name][self.site.code]
             except:
                 raise NoUsername(
 u"""ERROR: Username for %s:%s is undefined.
 If you have an account for that site, please add a line to user-config.py:
 
 usernames['%s']['%s'] = 'myUsername'"""
-                        % (self.site.family.name, self.site.language(),
-                           self.site.family.name, self.site.language()))
+                        % (self.site.family.name, self.site.code,
+                           self.site.family.name, self.site.code))
         self.password = password
         if getattr(config, 'password_file', ''):
             self.readPassword()
@@ -100,8 +100,8 @@
         the policy on the respective wiki.
         """
         return True # DEBUG
-        if botList.has_key(self.site.family.name) and botList[self.site.family.name].has_key(self.site.language()):
-            botListPageTitle = botList[self.site.family.name][self.site.language()]
+        if botList.has_key(self.site.family.name) and botList[self.site.family.name].has_key(self.site.code):
+            botListPageTitle = botList[self.site.family.name][self.site.code]
             botListPage = pywikibot.Page(self.site, botListPageTitle)
             for linkedPage in botListPage.linkedPages():
                 if linkedPage.titleWithoutNamespace() == self.username:
@@ -189,7 +189,7 @@
         """
         filename = config.datafilepath('%s-%s-%s-login.data'
                                        % (self.site.family.name,
-                                          self.site.language(),
+                                          self.site.code,
                                           self.username))
         f = open(filename, 'w')
         f.write(data)
@@ -217,7 +217,7 @@
             if len(entry) == 2:
                 if entry[0] == self.username: self.password = entry[1]
             elif len(entry) == 4:
-                if entry[0] == self.site.lang and \
+                if entry[0] == self.site.code and \
                   entry[1] == self.site.family.name and \
                   entry[2] == self.username:
                     self.password = entry[3]
@@ -238,7 +238,7 @@
             logging.info(u"Should be logged in now")
             # Show a warning according to the local bot policy
             if not self.botAllowed():
-                logging.error(u'*** Your username is not listed on [[%s]].\n*** Please make sure you are allowed to use the robot before actually using it!' % botList[self.site.family.name][self.site.lang])
+                logging.error(u'*** Your username is not listed on [[%s]].\n*** Please make sure you are allowed to use the robot before actually using it!' % botList[self.site.family.name][self.site.code])
             return True
         else:
             logging.error(u"Login failed. Wrong password or CAPTCHA answer?")

Modified: branches/rewrite/pywikibot/page.py
===================================================================
--- branches/rewrite/pywikibot/page.py	2008-05-28 12:28:34 UTC (rev 5452)
+++ branches/rewrite/pywikibot/page.py	2008-05-28 13:23:58 UTC (rev 5453)
@@ -155,12 +155,12 @@
             if forceInterwiki or (
                     allowInterwiki and self.site() != pywikibot.Site()):
                 if self.site().family != pywikibot.Site().family \
-                        and self.site().family.name != self.site().language():
+                        and self.site().family.name != self.site().code:
                     return u'[[%s:%s:%s]]' % (self.site().family.name,
-                                              self.site().language(),
+                                              self.site().code,
                                               self._title)
                 else:
-                    return u'[[%s:%s]]' % (self.site().language(),
+                    return u'[[%s:%s]]' % (self.site().code,
                                            self._title)
             elif textlink and (self.isImage() or self.isCategory()):
                     return u'[[:%s]]' % title
@@ -231,7 +231,7 @@
         if not hasattr(self, '_autoFormat'):
             from pywikibot import date
             self._autoFormat = date.getAutoFormat(
-                                        self.site().language(),
+                                        self.site().code,
                                         self.title(withNamespace=False)
                                     )
         return self._autoFormat
@@ -416,7 +416,7 @@
 
         """
         if not hasattr(self, '_isDisambig'):
-            locdis = self.site().family.disambig( self.site().lang )
+            locdis = self.site().family.disambig(self.site().code)
             for template in self.templates():
                 tn = template.title(withNamespace=False)
                 if tn in locdis:
@@ -1393,7 +1393,7 @@
                 if prefix in fam.langs.keys():
                     newsite = pywikibot.Site(prefix, fam)
                 else:
-                    otherlang = self.site.language()
+                    otherlang = self.site.code
                     familyName = fam.get_known_families(site=self.site)[prefix]
                     if familyName in ['commons', 'meta']:
                         otherlang = familyName

Modified: branches/rewrite/pywikibot/site.py
===================================================================
--- branches/rewrite/pywikibot/site.py	2008-05-28 12:28:34 UTC (rev 5452)
+++ branches/rewrite/pywikibot/site.py	2008-05-28 13:23:58 UTC (rev 5453)
@@ -74,28 +74,28 @@
         @type user: str
 
         """
-        self._lang = code.lower()
+        self.__code = code.lower()
         if isinstance(fam, basestring) or fam is None:
             self.__family = Family(fam, fatal=False)
         else:
             self.__family = fam
 
         # if we got an outdated language code, use the new one instead.
-        if self.__family.obsolete.has_key(self._lang):
-            if self.__family.obsolete[self._lang] is not None:
-                self._lang = self.__family.obsolete[self._lang]
+        if self.__family.obsolete.has_key(self.__code):
+            if self.__family.obsolete[self.__code] is not None:
+                self.__code = self.__family.obsolete[self.__code]
             else:
                 # no such language anymore
                 raise NoSuchSite("Language %s in family %s is obsolete"
-                                 % (self._lang, self.__family.name))
-        if self._lang not in self.languages():
-            if self._lang == 'zh-classic' and 'zh-classical' in self.languages():
-                self._lang = 'zh-classical'
+                                 % (self.__code, self.__family.name))
+        if self.__code not in self.languages():
+            if self.__code == 'zh-classic' and 'zh-classical' in self.languages():
+                self.__code = 'zh-classical'
                 # database hack (database is varchar[10] -> zh-classical
                 # is cut to zh-classic.
             else:
                 raise NoSuchSite("Language %s does not exist in family %s"
-                                 % (self._lang, self.__family.name))
+                                 % (self.__code, self.__family.name))
 
         self._username = user
 
@@ -117,15 +117,13 @@
 
     @property
     def family(self):
-        """Return the associated Family object."""
+        """The Family object for this Site's wiki family."""
         return self.__family
 
-    def language(self):
-        """Return the site's language code."""
-        # N.B. this code does not always identify a language as such, but
-        #      may identify a wiki that is part of any family grouping
-        # FIXME: need to separate language (for L18N purposes) from code
-        return self._lang
+    @property
+    def code(self):
+        """The identifying code for this Site."""
+        return self.__code
 
     def user(self):
         """Return the currently-logged in bot user, or None."""
@@ -140,7 +138,7 @@
         try:
             method = getattr(self.family, attr)
             f = lambda *args, **kwargs: \
-                       method(self.language(), *args, **kwargs)
+                       method(self.code, *args, **kwargs)
             if hasattr(method, "__doc__"):
                 f.__doc__ = method.__doc__
             return f
@@ -150,19 +148,19 @@
 
     def sitename(self):
         """Return string representing this Site's name and language."""
-        return self.family.name+':'+self.language()
+        return self.family.name+':'+self.code
 
     __str__ = sitename
 
     def __repr__(self):
-        return 'Site("%s", "%s")' % (self.language(), self.family.name)
+        return 'Site("%s", "%s")' % (self.code, self.family.name)
 
     def __hash__(self):
         return hash(repr(self))
 
     def linktrail(self):
         """Return regex for trailing chars displayed as part of a link."""
-        return self.family.linktrail(self.language())
+        return self.family.linktrail(self.code)
 
     def languages(self):
         """Return list of all valid language codes for this site's Family."""
@@ -205,11 +203,11 @@
             if self.language() == 'ar':
                 # It won't work with REDIRECT[[]] but it work with the local,
                 # if problems, try to find a work around. FixMe!
-                return self.family.redirect.get(self.language(), [u"تحويل"])[0]
+                return self.family.redirect.get(self.code, [u"تحويل"])[0]
             else:
-                return self.family.redirect.get(self.language(), [u"REDIRECT"])[0]
+                return self.family.redirect.get(self.code, [u"REDIRECT"])[0]
         else:
-            return self.family.redirect.get(self.language(), None)
+            return self.family.redirect.get(self.code, None)
 
     def lock_page(self, page, block=True):
         """Lock page for writing.  Must be called before writing any page.
@@ -350,7 +348,7 @@
 
 # ANYTHING BELOW THIS POINT IS NOT YET IMPLEMENTED IN __init__()
         self._mediawiki_messages = {}
-        self.nocapitalize = self._lang in self.family.nocapitalize
+        self.nocapitalize = self.__code in self.family.nocapitalize
         self._userData = [False, False]
         self._userName = [None, None]
         self._isLoggedIn = [None, None]
@@ -488,6 +486,11 @@
     def case(self):
         return self.getsiteinfo()['case']
 
+    def language(self):
+        """Return the code for the language of this Site."""
+        # N.B. this code may or may not be the same as self.code
+        return self.getsiteinfo()['lang']
+
     def namespaces(self):
         """Return dict of valid namespaces on this wiki."""
         self.getsiteinfo()
@@ -1651,21 +1654,21 @@
         try:
             if sysop:
                 try:
-                    username = config.sysopnames[self.family.name][self.language()]
+                    username = config.sysopnames[self.family.name][self.code]
                 except KeyError:
                     raise NoUsername("""\
 You tried to perform an action that requires admin privileges, but you haven't
 entered your sysop name in your user-config.py. Please add
 sysopnames['%s']['%s']='name' to your user-config.py"""
-                                     % (self.family.name, self.language()))
+                                     % (self.family.name, self.code))
             else:
-                username = config.usernames[self.family.name][self.language()]
+                username = config.usernames[self.family.name][self.code]
         except KeyError:
             self._cookies[index] = None
             self._isLoggedIn[index] = False
         else:
             tmp = '%s-%s-%s-login.data' % (
-                    self.family.name, self.language(), username)
+                    self.family.name, self.code, username)
             fn = config.datafilepath('login-data', tmp)
             if not os.path.exists(fn):
                 self._cookies[index] = None
@@ -2491,8 +2494,8 @@
         Use optional Site argument 'othersite' to generate an interwiki link.
 
         """
-        if othersite and othersite.lang != self.language():
-            return u'[[%s:%s]]' % (self.language(), title)
+        if othersite and othersite.code != self.code:
+            return u'[[%s:%s]]' % (self.code, title)
         else:
             return u'[[%s]]' % title
 
@@ -2518,7 +2521,7 @@
         if self.ns_index(first):
             return False
         if first in interlangTargetFamily.langs:
-            if first == self.language():
+            if first == self.code:
                 return self.isInterwikiLink(rest)
             else:
                 return True
@@ -2541,10 +2544,10 @@
             red = u"تحويل"
         try:
             if redDefault == red:
-                redirKeywords = [red] + self.family.redirect[self.language()]
+                redirKeywords = [red] + self.family.redirect[self.code]
                 redirKeywordsR = r'(?:' + '|'.join(redirKeywords) + ')'
             else:
-                redirKeywords = [red] + self.family.redirect[self.language()]
+                redirKeywords = [red] + self.family.redirect[self.code]
                 redirKeywordsR = r'(?:' + redDefault + '|'.join(redirKeywords) + ')'
         except KeyError:
             # no localized keyword for redirects
@@ -2561,7 +2564,7 @@
 
     def version(self):
         """Return MediaWiki version number as a string."""
-        return self.family.version(self.language())
+        return self.family.version(self.code)
 
     def versionnumber(self):
         """Return an int identifying MediaWiki version.
@@ -2570,7 +2573,7 @@
         number; i.e., 'X' in version '1.X.Y'
 
         """
-        return self.family.versionnumber(self.language())
+        return self.family.versionnumber(self.code)
 
     def live_version(self):
         """Return the 'real' version number found on [[Special:Version]]
@@ -2590,7 +2593,7 @@
                 self._mw_version = (int(m.group(1)), int(m.group(2)),
                                         m.group(3))
             else:
-                self._mw_version = self.family.version(self.language()).split(".")
+                self._mw_version = self.family.version(self.code).split(".")
         return self._mw_version
 
     def checkCharset(self, charset):
@@ -2607,34 +2610,34 @@
 
     def shared_image_repository(self):
         """Return a tuple of image repositories used by this site."""
-        return self.family.shared_image_repository(self.language())
+        return self.family.shared_image_repository(self.code)
 
     def __cmp__(self, other):
         """Perform equality and inequality tests on Site objects."""
         if not isinstance(other, Site):
             return 1
         if self.family == other.family:
-            return cmp(self.language(), other.lang)
+            return cmp(self.code, other.code)
         return cmp(self.family.name, other.family.name)
 
     def category_on_one_line(self):
         """Return True if this site wants all category links on one line."""
-        return self.language() in self.family.category_on_one_line
+        return self.code in self.family.category_on_one_line
 
     def interwiki_putfirst(self):
         """Return list of language codes for ordering of interwiki links."""
-        return self.family.interwiki_putfirst.get(self.language(), None)
+        return self.family.interwiki_putfirst.get(self.code, None)
 
     def interwiki_putfirst_doubled(self, list_of_links):
         # TODO: is this even needed?  No family in the framework has this
         # dictionary defined!
-        if self.family.interwiki_putfirst_doubled.has_key(self.language()):
-            if len(list_of_links) >= self.family.interwiki_putfirst_doubled[self.language()][0]:
+        if self.family.interwiki_putfirst_doubled.has_key(self.code):
+            if len(list_of_links) >= self.family.interwiki_putfirst_doubled[self.code][0]:
                 list_of_links2 = []
                 for lang in list_of_links:
-                    list_of_links2.append(lang.language())
+                    list_of_links2.append(lang.code)
                 list = []
-                for lang in self.family.interwiki_putfirst_doubled[self.language()][1]:
+                for lang in self.family.interwiki_putfirst_doubled[self.code][1]:
                     try:
                         list.append(list_of_links[list_of_links2.index(lang)])
                     except ValueError:
@@ -2658,7 +2661,7 @@
         import catlib
         try:
             return catlib.Category(self,
-                    self.namespace(14)+':'+self.family.disambcatname[self.language()])
+                    self.namespace(14)+':'+self.family.disambcatname[self.code])
         except KeyError:
             raise NoPage(u'No page %s.' % page)
 





More information about the Pywikipedia-l mailing list