jenkins-bot has submitted this change and it was merged.
Change subject: Introduce and use tools.first_lower() and tools.first_upper()
......................................................................
Introduce and use tools.first_lower() and tools.first_upper()
Standardize two simple functions that have been
scattered over several scripts for a while.
Change-Id: Iddfe30fcbca2334399841bd15a878db4b37def59
---
M pwb.py
M pywikibot/date.py
M pywikibot/page.py
M pywikibot/site.py
M pywikibot/tools/__init__.py
M scripts/casechecker.py
M scripts/cosmetic_changes.py
M scripts/disambredir.py
M scripts/fixing_redirects.py
M scripts/interwiki.py
M scripts/solve_disambiguation.py
M tests/pwb/print_env.py
12 files changed, 54 insertions(+), 48 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pwb.py b/pwb.py
index b1bb52c..b15b927 100644
--- a/pwb.py
+++ b/pwb.py
@@ -100,6 +100,7 @@
path = os.path.abspath(path)
if path[0] != '/':
# normalise Windows drive letter
+ # TODO: use pywikibot.tools.first_upper
path = path[0].upper() + path[1:]
return path
diff --git a/pywikibot/date.py b/pywikibot/date.py
index 976edef..75fdc9d 100644
--- a/pywikibot/date.py
+++ b/pywikibot/date.py
@@ -20,6 +20,8 @@
import re
import sys
+from pywikibot.tools import first_lower, first_upper
+
if sys.version_info[0] > 2:
unicode = str
basestring = (str,)
@@ -1982,9 +1984,9 @@
if makeUpperCase is None:
f = lambda s: s
elif makeUpperCase:
- f = lambda s: s[0].upper() + s[1:]
+ f = first_upper
else:
- f = lambda s: s[0].lower() + s[1:]
+ f = first_lower
return [pattern % f(monthName(lang, m)) for m in range(1, 13)]
#
@@ -2337,9 +2339,9 @@
if ignoreFirstLetterCase:
try:
if title[0].isupper():
- title = title[0].lower() + title[1:]
+ title = first_lower(title)
else:
- title = title[0].upper() + title[1:]
+ title = first_upper(title)
return getAutoFormat(lang, title, ignoreFirstLetterCase=False)
except:
pass
diff --git a/pywikibot/page.py b/pywikibot/page.py
index a2eb04c..e089fc2 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -51,7 +51,7 @@
from pywikibot.tools import (
UnicodeMixin, DotReadableDict,
ComparableMixin, deprecated, deprecate_arg, deprecated_args,
- remove_last_args, _NotImplementedWarning,
+ first_upper, remove_last_args, _NotImplementedWarning,
OrderedDict, Counter,
)
from pywikibot.tools.ip import ip_regexp # noqa & deprecated
@@ -784,20 +784,19 @@
regex = re.compile('\(\((.+?)\)\)')
content = disambigpages.get()
for index in regex.findall(content):
- indexes.add(index[:1].upper() + index[1:])
+ indexes.add(first_upper(index))
self.site._indextemplates = indexes
else:
message = self.site.mediawiki_message(
'disambiguationspage').split(':', 1)[1]
# add the default template(s) for default mw message
# only
- disambigs = set([message[:1].upper() +
- message[1:]]) | default
+ disambigs = set([first_upper(message)]) | default
self.site._disambigtemplates = disambigs
else:
# Normalize template capitalization
self.site._disambigtemplates = set(
- t[:1].upper() + t[1:] for t in distl
+ first_upper(t) for t in distl
)
templates = set(tl.title(withNamespace=False)
for tl in self.templates())
@@ -4575,7 +4574,7 @@
"title")
if self._site.namespaces[self._namespace].case == 'first-letter':
- t = t[:1].upper() + t[1:]
+ t = first_upper(t)
self._title = t
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 5848169..b9fe830 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -34,7 +34,7 @@
from pywikibot.tools import (
itergroup, UnicodeMixin, ComparableMixin, SelfCallDict, SelfCallString,
deprecated, deprecate_arg, deprecated_args, remove_last_args,
- redirect_func, manage_wrapping, MediaWikiVersion, normalize_username,
+ redirect_func, manage_wrapping, MediaWikiVersion, first_upper,
normalize_username,
)
from pywikibot.tools.ip import is_IP
from pywikibot.throttle import Throttle
@@ -681,7 +681,7 @@
"""Return list of language codes that can be used in interwiki
links."""
nsnames = [name for name in self.namespaces().values()]
return [lang for lang in self.languages()
- if lang[:1].upper() + lang[1:] not in nsnames]
+ if first_upper(lang) not in nsnames]
def _cache_interwikimap(self, force=False):
"""Cache the interwikimap with usable site instances."""
@@ -928,8 +928,8 @@
# If the namespace has a case definition it's overriding the site's
# case definition
if ns1_obj.case == 'first-letter':
- name1 = name1[:1].upper() + name1[1:]
- name2 = name2[:1].upper() + name2[1:]
+ name1 = first_upper(name1)
+ name2 = first_upper(name2)
return name1 == name2
# namespace shortcuts for backwards-compatibility
diff --git a/pywikibot/tools/__init__.py b/pywikibot/tools/__init__.py
index 22d6c4d..53513ac 100644
--- a/pywikibot/tools/__init__.py
+++ b/pywikibot/tools/__init__.py
@@ -241,12 +241,30 @@
raise AttributeError('%s.raw not set' % self.__class__.__name__)
+def first_lower(string):
+ """
+ Return a string with the first character uncapitalized.
+
+ Empty strings are supported. The original string is not changed.
+ """
+ return string[:1].lower() + string[1:]
+
+
+def first_upper(string):
+ """
+ Return a string with the first character capitalized.
+
+ Empty strings are supported. The original string is not changed.
+ """
+ return string[:1].upper() + string[1:]
+
+
def normalize_username(username):
"""Normalize the username."""
if not username:
return None
username = re.sub('[_ ]+', ' ', username).strip()
- return username[0].upper() + username[1:]
+ return first_upper(username)
class MediaWikiVersion(Version):
diff --git a/scripts/casechecker.py b/scripts/casechecker.py
index 27be8e0..b4b608b 100755
--- a/scripts/casechecker.py
+++ b/scripts/casechecker.py
@@ -16,6 +16,7 @@
import pywikibot
from pywikibot import i18n
from pywikibot.data import api
+from pywikibot.tools import first_lower, first_upper
if sys.version_info[0] > 2:
xrange = range
@@ -805,10 +806,8 @@
if len(frmParts[i]) != len(toParts[i]):
raise ValueError(u'Splitting parts do not match word length')
if len(frmParts[i]) > 0:
- text = text.replace(frmParts[i][0].lower() + frmParts[i][1:],
- toParts[i][0].lower() + toParts[i][1:])
- text = text.replace(frmParts[i][0].upper() + frmParts[i][1:],
- toParts[i][0].upper() + toParts[i][1:])
+ text = text.replace(first_lower(frmParts[i]),
first_lower(toParts[i]))
+ text = text.replace(first_upper(frmParts[i]),
first_upper(toParts[i]))
return text
diff --git a/scripts/cosmetic_changes.py b/scripts/cosmetic_changes.py
index 14e88fb..bb99a30 100755
--- a/scripts/cosmetic_changes.py
+++ b/scripts/cosmetic_changes.py
@@ -82,7 +82,7 @@
from pywikibot import config, i18n, textlib, pagegenerators
from pywikibot.bot import ExistingPageBot, NoRedirectPageBot
from pywikibot.page import url2unicode
-from pywikibot.tools import deprecate_arg
+from pywikibot.tools import deprecate_arg, first_lower, first_upper
warning = """
ATTENTION: You can run this script as a stand-alone for testing purposes.
@@ -408,7 +408,7 @@
item = namespaces[i].replace(' ', '[ _]')
item = u'[%s%s]' % (item[0], item[0].lower()) + item[1:]
namespaces[i] = item
- namespaces.append(thisNs[0].lower() + thisNs[1:])
+ namespaces.append(first_lower(thisNs))
if thisNs and namespaces:
text = textlib.replaceExcept(
text,
@@ -510,8 +510,7 @@
label += trailingChars
if titleWithSection == label or \
- titleWithSection[0].lower() + \
- titleWithSection[1:] == label:
+ first_lower(titleWithSection) == label:
newLink = "[[%s]]" % label
# Check if we can create a link with trailing characters
# instead of a pipelink
@@ -528,8 +527,7 @@
# which determines if the link target is written in
# uppercase
if self.site.sitename() == 'wikipedia:de':
- titleWithSection = (titleWithSection[0].upper() +
- titleWithSection[1:])
+ titleWithSection = first_upper(titleWithSection)
newLink = "[[%s|%s]]" % (titleWithSection, label)
# re-add spaces that were pulled out of the link.
# Examples:
diff --git a/scripts/disambredir.py b/scripts/disambredir.py
index e1b2db9..fe5bd49 100755
--- a/scripts/disambredir.py
+++ b/scripts/disambredir.py
@@ -22,6 +22,7 @@
import re
import pywikibot
from pywikibot import i18n, pagegenerators
+from pywikibot.tools import first_lower, first_upper as firstcap
msg = {
'ar': u'تغيير التحويلات في صفحة توضيح',
@@ -37,10 +38,6 @@
'uk': u'Зміна перенаправлень на сторінці багатозначності',
'zh': u'機器人: 修改消歧義頁中的重定向連結',
}
-
-
-def firstcap(string):
- return string[0].upper() + string[1:]
def treat(text, linkedPage, targetPage):
@@ -109,8 +106,7 @@
if link_text[0].isupper():
new_page_title = targetPage.title()
else:
- new_page_title = (targetPage.title()[0].lower() +
- targetPage.title()[1:])
+ new_page_title = first_lower(targetPage.title())
if choice == 'r' and trailing_chars:
newlink = "[[%s%s]]%s" % (new_page_title, section, trailing_chars)
elif choice == 'r' or (new_page_title == link_text and not section):
diff --git a/scripts/fixing_redirects.py b/scripts/fixing_redirects.py
index 6fbe7bd..ebfb555 100755
--- a/scripts/fixing_redirects.py
+++ b/scripts/fixing_redirects.py
@@ -28,6 +28,7 @@
import pywikibot
from pywikibot import pagegenerators
from pywikibot import i18n
+from pywikibot.tools import first_lower, first_upper as firstcap
# This is required for the text that is shown when you run this script
# with the parameter -help.
@@ -56,10 +57,6 @@
'vi': u'Wikipedia:Bài_viết_chọn_lọc',
'zh': u'Wikipedia:特色条目',
}
-
-
-def firstcap(string):
- return string[0].upper() + string[1:]
def treat(text, linkedPage, targetPage):
@@ -118,8 +115,7 @@
if link_text[0].isupper():
new_page_title = targetPage.title()
else:
- new_page_title = targetPage.title()[0].lower() + \
- targetPage.title()[1:]
+ new_page_title = first_lower(targetPage.title())
# remove preleading ":"
if new_page_title[0] == ':':
diff --git a/scripts/interwiki.py b/scripts/interwiki.py
index aa3d46a..bae382f 100755
--- a/scripts/interwiki.py
+++ b/scripts/interwiki.py
@@ -357,6 +357,7 @@
import socket
import pywikibot
from pywikibot import config, i18n, pagegenerators, textlib, interwiki_graph,
titletranslate
+from pywikibot.tools import first_upper
if sys.version_info[0] > 2:
unicode = str
@@ -2215,7 +2216,7 @@
if self.generateUntil:
until = self.generateUntil
if page.site.lang not in page.site.family.nocapitalize:
- until = until[0].upper() + until[1:]
+ until = first_upper(until)
if page.title(withNamespace=False) > until:
raise StopIteration
self.add(page, hints=globalvar.hints)
diff --git a/scripts/solve_disambiguation.py b/scripts/solve_disambiguation.py
index d297680..b91f0b3 100755
--- a/scripts/solve_disambiguation.py
+++ b/scripts/solve_disambiguation.py
@@ -85,7 +85,7 @@
import pywikibot
from pywikibot import editor as editarticle
-from pywikibot.tools import concat_options
+from pywikibot.tools import concat_options, first_lower, first_upper as
firstcap
from pywikibot import pagegenerators, config, i18n
from pywikibot.bot import Bot, QuitKeyboardInterrupt
@@ -341,15 +341,11 @@
}
-def firstcap(string):
- return string[0].upper() + string[1:]
-
-
def correctcap(link, text):
# If text links to a page with title link uncapitalized, uncapitalize link,
# otherwise capitalize it
linkupper = link.title()
- linklower = linkupper[0].lower() + linkupper[1:]
+ linklower = first_lower(linkupper)
if "[[%s]]" % linklower in text or "[[%s|" % linklower in text:
return linklower
else:
@@ -809,8 +805,7 @@
new_page_title = repPl.title()
else:
new_page_title = repPl.title()
- new_page_title = (new_page_title[0].lower() +
- new_page_title[1:])
+ new_page_title = first_lower(new_page_title)
if new_page_title not in new_targets:
new_targets.append(new_page_title)
if replaceit and trailing_chars:
diff --git a/tests/pwb/print_env.py b/tests/pwb/print_env.py
index e61230d..3bdf8ad 100644
--- a/tests/pwb/print_env.py
+++ b/tests/pwb/print_env.py
@@ -5,10 +5,11 @@
import os
import sys
+from pywikibot.tools import first_upper
_pwb_dir = os.path.abspath(os.path.join(
os.path.split(__file__)[0], '..', '..'))
-_pwb_dir = _pwb_dir[0].upper() + _pwb_dir[1:]
+_pwb_dir = first_upper(_pwb_dir)
print('os.environ:')
for k, v in sorted(os.environ.items()):
@@ -25,7 +26,7 @@
if path == '' or path.startswith('.'):
continue
# Normalise DOS drive letter
- path = path[0].upper() + path[1:]
+ path = first_upper(path)
if path.startswith(_pwb_dir):
continue
print(path)
--
To view, visit https://gerrit.wikimedia.org/r/205004
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Iddfe30fcbca2334399841bd15a878db4b37def59
Gerrit-PatchSet: 6
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Ricordisamoa <[email protected]>
Gerrit-Reviewer: John Vandenberg <[email protected]>
Gerrit-Reviewer: Ladsgroup <[email protected]>
Gerrit-Reviewer: Merlijn van Deen <[email protected]>
Gerrit-Reviewer: Ricordisamoa <[email protected]>
Gerrit-Reviewer: XZise <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot <>
_______________________________________________
Pywikibot-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/pywikibot-commits