jenkins-bot has submitted this change and it was merged.
Change subject: [FIX] W503 errors
......................................................................
[FIX] W503 errors
With a recent version of PEP8 (and thus flake8) binary operators (like
and) are not allowed at the start of a line and instead at the end of
the previous one. Double quotes in the affected lines too were changed.
Change-Id: I5d89afa1d7bd4711a80d8b6c831ee63afe440ef5
---
M generate_family_file.py
M pywikibot/data/api.py
M pywikibot/data/wikidataquery.py
M pywikibot/page.py
M pywikibot/pagegenerators.py
M pywikibot/site.py
M pywikibot/userinterfaces/win32_unicode.py
M scripts/archivebot.py
M scripts/category_redirect.py
M scripts/commonscat.py
M scripts/interwiki.py
M scripts/solve_disambiguation.py
M scripts/transferbot.py
M scripts/unlink.py
M tests/__init__.py
M tests/aspects.py
M tests/script_tests.py
M tests/site_tests.py
18 files changed, 93 insertions(+), 100 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/generate_family_file.py b/generate_family_file.py
index 28af939..fa4619b 100644
--- a/generate_family_file.py
+++ b/generate_family_file.py
@@ -143,8 +143,8 @@
print(wiki['prefix'], wiki['url'])
do_langs = raw_input("Which languages do you want: ")
self.langs = [wiki for wiki in self.langs
- if wiki['prefix'] in do_langs
- or wiki['url'] == w.iwpath]
+ if wiki['prefix'] in do_langs or
+ wiki['url'] == w.iwpath]
else:
self.langs = [wiki for wiki in self.langs
if wiki[u'url'] == w.iwpath]
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index a84b08c..4433982 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -332,8 +332,8 @@
for mod in module_batch]
else:
params['modules'] = [mod for mod in module_batch
- if mod not in self._query_modules
- and mod not in self.root_modules]
+ if mod not in self._query_modules and
+ mod not in self.root_modules]
params['querymodules'] = [mod for mod in module_batch
if mod in self._query_modules]
@@ -818,8 +818,8 @@
self["assert"] = 'user' # make sure user is logged in
if (self.site.protocol() == 'http' and (config.use_SSL_always or (
- self.action == 'login' and config.use_SSL_onlogin))
- and self.site.family.name in config.available_ssl_project):
+ self.action == 'login' and config.use_SSL_onlogin)) and
+ self.site.family.name in config.available_ssl_project):
self.site = EnableSSLSiteWrapper(self.site)
@classmethod
@@ -1031,9 +1031,9 @@
def __str__(self):
"""Return a string representation."""
- return unquote(self.site.scriptpath()
- + "/api.php?"
- + self._http_param_string())
+ return unquote(self.site.scriptpath() +
+ '/api.php?' +
+ self._http_param_string())
def __repr__(self):
"""Return internal representation."""
@@ -1267,10 +1267,10 @@
else:
self.site._userinfo = result['query']['userinfo']
status = self.site._loginstatus # save previous login status
- if (("error" in result
- and result["error"]["code"].endswith("limit"))
- or (status >= 0
- and self.site._userinfo['name'] != self.site._username[status])):
+ if (('error' in result and
+ result['error']['code'].endswith('limit')) or
+ (status >= 0 and
+ self.site._userinfo['name'] != self.site._username[status])):
# user is no longer logged in (session expired?)
# reset userinfo, then make user log in again
del self.site._userinfo
diff --git a/pywikibot/data/wikidataquery.py b/pywikibot/data/wikidataquery.py
index 5ad6bed..b9fe073 100644
--- a/pywikibot/data/wikidataquery.py
+++ b/pywikibot/data/wikidataquery.py
@@ -316,8 +316,8 @@
if not self.isOrContainsOnlyTypes(item, [int, ItemPage]):
raise TypeError("The item paramter must contain or be integer IDs "
"or page.ItemPages")
- elif (not self.isOrContainsOnlyTypes(forward, [int, PropertyPage])
- or not self.isOrContainsOnlyTypes(reverse, [int, PropertyPage])):
+ elif (not self.isOrContainsOnlyTypes(forward, [int, PropertyPage]) or
+ not self.isOrContainsOnlyTypes(reverse, [int, PropertyPage])):
raise TypeError("The forward and reverse parameters must contain "
"or be integer IDs or page.PropertyPages")
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 1befe68..1741107 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -218,8 +218,8 @@
target_family = config.family
if forceInterwiki or \
(allowInterwiki and
- (self.site.family.name != target_family
- or self.site.code != target_code)):
+ (self.site.family.name != target_family or
+ self.site.code != target_code)):
if self.site.family.name != target_family \
and self.site.family.name != self.site.code:
title = u'%s:%s:%s' % (self.site.family.name,
@@ -1559,8 +1559,8 @@
"""
if hasattr(self, "_deletedRevs"):
if timestamp in self._deletedRevs and (
- (not retrieveText)
- or "content" in self._deletedRevs[timestamp]):
+ (not retrieveText) or
+ 'content' in self._deletedRevs[timestamp]):
return self._deletedRevs[timestamp]
for item in self.site.deletedrevs(self, start=timestamp,
get_text=retrieveText, total=1):
@@ -4521,13 +4521,13 @@
# * with 'relative' URLs. Forbid them explicitly.
if u'.' in t and (
- t == u'.' or t == u'..'
- or t.startswith(u"./")
- or t.startswith(u"../")
- or u"/./" in t
- or u"/../" in t
- or t.endswith(u"/.")
- or t.endswith(u"/..")
+ t == u'.' or t == u'..' or
+ t.startswith(u'./') or
+ t.startswith(u'../') or
+ u'/./' in t or
+ u'/../' in t or
+ t.endswith(u'/.') or
+ t.endswith(u'/..')
):
raise pywikibot.InvalidTitle(
u"(contains . / combinations): '%s'"
diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index 9a66176..a87a05a 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -469,8 +469,7 @@
if not fileLinksPageTitle:
fileLinksPageTitle = i18n.input(
'pywikibot-enter-file-links-processing')
- if fileLinksPageTitle.startswith(self.site.namespace(6)
- + ":"):
+ if fileLinksPageTitle.startswith(self.site.namespace(6) + ':'):
fileLinksPage = pywikibot.FilePage(self.site,
fileLinksPageTitle)
else:
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 80c627c..ffedbaf 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -455,8 +455,8 @@
# int(None) raises TypeError; however, bool needs special handling.
result = [NotImplemented if isinstance(ns, bool) else
Namespace.lookup_name(ns, namespaces)
- if isinstance(ns, basestring)
- and not ns.lstrip('-').isdigit() else
+ if isinstance(ns, basestring) and
+ not ns.lstrip('-').isdigit() else
namespaces[int(ns)] if int(ns) in namespaces
else None
for ns in identifiers]
@@ -1702,10 +1702,9 @@
- blockinfo: present if user is blocked (dict)
"""
- if (not hasattr(self, "_userinfo")
- or "rights" not in self._userinfo
- or self._userinfo['name']
- != self._username["sysop" in self._userinfo["groups"]]):
+ if (not hasattr(self, '_userinfo') or
+ 'rights' not in self._userinfo or
+ self._userinfo['name'] != self._username['sysop' in self._userinfo['groups']]):
uirequest = api.Request(
site=self,
action="query",
@@ -1788,8 +1787,8 @@
@rtype: C{set} of L{Namespace}
"""
# TODO: Integrate into _userinfo
- if (force or not hasattr(self, "_useroptions")
- or self.user() != self._useroptions['_name']):
+ if (force or not hasattr(self, '_useroptions') or
+ self.user() != self._useroptions['_name']):
uirequest = api.Request(
site=self,
action="query",
@@ -1806,8 +1805,8 @@
self._useroptions['_name'] = (
None if 'anon' in uidata['query']['userinfo'] else
uidata['query']['userinfo']['name'])
- return set(ns for ns in self.namespaces().values() if ns.id >= 0
- and self._useroptions['searchNs{0}'.format(ns.id)] in ['1', True])
+ return set(ns for ns in self.namespaces().values() if ns.id >= 0 and
+ self._useroptions['searchNs{0}'.format(ns.id)] in ['1', True])
def assert_valid_iter_params(self, msg_prefix, start, end, reverse):
"""Validate iterating API parameters."""
@@ -3337,13 +3336,12 @@
if prefix:
apgen.request["gapprefix"] = prefix
if filterredir is not None:
- apgen.request["gapfilterredir"] = (filterredir
- and "redirects"
- or "nonredirects")
+ apgen.request['gapfilterredir'] = ('redirects' if filterredir else
+ 'nonredirects')
if filterlanglinks is not None:
- apgen.request["gapfilterlanglinks"] = (filterlanglinks
- and "withlanglinks"
- or "withoutlanglinks")
+ apgen.request['gapfilterlanglinks'] = ('withlanglinks'
+ if filterlanglinks else
+ 'withoutlanglinks')
if isinstance(minsize, int):
apgen.request["gapminsize"] = str(minsize)
if isinstance(maxsize, int):
@@ -3602,8 +3600,8 @@
"""
iuargs = dict(giutitle=image.title(withSection=False))
if filterredir is not None:
- iuargs["giufilterredir"] = (filterredir and "redirects"
- or "nonredirects")
+ iuargs['giufilterredir'] = ('redirects' if filterredir else
+ 'nonredirects')
iugen = self._generator(api.PageGenerator, type_arg="imageusage",
namespaces=namespaces, step=step,
total=total, g_content=content, **iuargs)
@@ -4893,8 +4891,8 @@
break
else: # not chunked upload
file_contents = f.read()
- filetype = (mimetypes.guess_type(source_filename)[0]
- or 'application/octet-stream')
+ filetype = (mimetypes.guess_type(source_filename)[0] or
+ 'application/octet-stream')
additional_parameters = {
'mime_params': {
'file': (file_contents,
diff --git a/pywikibot/userinterfaces/win32_unicode.py b/pywikibot/userinterfaces/win32_unicode.py
index 64016f7..3e77812 100755
--- a/pywikibot/userinterfaces/win32_unicode.py
+++ b/pywikibot/userinterfaces/win32_unicode.py
@@ -83,8 +83,8 @@
def not_a_console(handle):
if handle == INVALID_HANDLE_VALUE or handle is None:
return True
- return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
- or GetConsoleMode(handle, byref(DWORD())) == 0)
+ return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
+ GetConsoleMode(handle, byref(DWORD())) == 0)
old_stdin_fileno = None
old_stdout_fileno = None
diff --git a/scripts/archivebot.py b/scripts/archivebot.py
index 993c454..e2508da 100644
--- a/scripts/archivebot.py
+++ b/scripts/archivebot.py
@@ -422,8 +422,8 @@
self.attributes[attr] = [value, out]
def saveables(self):
- return [a for a in self.attributes if self.attributes[a][1]
- and a != 'maxage']
+ return [a for a in self.attributes if self.attributes[a][1] and
+ a != 'maxage']
def attr2text(self):
return '{{%s\n%s\n}}' \
diff --git a/scripts/category_redirect.py b/scripts/category_redirect.py
index af0aca3..c68c8c7 100755
--- a/scripts/category_redirect.py
+++ b/scripts/category_redirect.py
@@ -437,12 +437,12 @@
newredirs.sort()
comment = i18n.twtranslate(self.site.code, self.maint_comment)
self.log_page.text = (u"\n== %i-%02i-%02iT%02i:%02i:%02iZ ==\n"
- % time.gmtime()[:6]
- + u"\n".join(self.log_text)
- + u"\n* New redirects since last report:\n"
- + u"\n".join(newredirs)
- + u"\n" + u"\n".join(self.problems)
- + u"\n" + self.get_log_text())
+ % time.gmtime()[:6] +
+ u'\n'.join(self.log_text) +
+ u'\n* New redirects since last report:\n' +
+ u'\n'.join(newredirs) +
+ u'\n' + u'\n'.join(self.problems) +
+ u'\n' + self.get_log_text())
self.log_page.save(comment)
if self.edit_requests:
edit_request_page.text = (self.edit_request_text
diff --git a/scripts/commonscat.py b/scripts/commonscat.py
index b078987..957983c 100755
--- a/scripts/commonscat.py
+++ b/scripts/commonscat.py
@@ -387,8 +387,8 @@
ipage = pywikibot.page.Page(ipageLink)
pywikibot.log("Looking for template on %s" % (ipage.title()))
try:
- if(not ipage.exists() or ipage.isRedirectPage()
- or ipage.isDisambig()):
+ if (not ipage.exists() or ipage.isRedirectPage() or
+ ipage.isDisambig()):
continue
commonscatLink = self.getCommonscatLink(ipage)
if not commonscatLink:
diff --git a/scripts/interwiki.py b/scripts/interwiki.py
index f17bc0c..becd5de 100755
--- a/scripts/interwiki.py
+++ b/scripts/interwiki.py
@@ -1726,8 +1726,8 @@
for (site, page) in new.items():
# edit restriction for some templates on zh-wiki where
# interlanguage keys are included by /doc subpage
- smallWikiAllowed = not (page.site.sitename() == 'wikipedia:zh'
- and page.namespace() == 10 and
+ smallWikiAllowed = not (page.site.sitename() == 'wikipedia:zh' and
+ page.namespace() == 10 and
u'Country data' in page.title(withNamespace=False))
# edit restriction on is-wiki
# https://is.wikipedia.org/wiki/Wikipediaspjall:V%C3%A9lmenni
diff --git a/scripts/solve_disambiguation.py b/scripts/solve_disambiguation.py
index ed1c814..fad491e 100644
--- a/scripts/solve_disambiguation.py
+++ b/scripts/solve_disambiguation.py
@@ -660,12 +660,10 @@
if not self.always:
# at the beginning of the link, start red color.
# at the end of the link, reset the color to default
- pywikibot.output(text[max(0, m.start() - context):
- m.start()]
- + '\03{lightred}'
- + text[m.start():m.end()]
- + '\03{default}'
- + text[m.end():m.end() + context])
+ pywikibot.output(
+ text[max(0, m.start() - context):m.start()] +
+ '\03{lightred}' + text[m.start():m.end()] +
+ '\03{default}' + text[m.end():m.end() + context])
options = ['#', 'r#', '[s]kip link', '[e]dit page',
'[n]ext page', '[u]nlink', '[q]uit']
if self.dn_template_str:
@@ -804,8 +802,8 @@
new_page_title = self.alternatives[choice]
repPl = pywikibot.Page(pywikibot.Link(new_page_title,
disambPage.site))
- if (new_page_title[0].isupper()
- or link_text[0].isupper()):
+ if (new_page_title[0].isupper() or
+ link_text[0].isupper()):
new_page_title = repPl.title()
else:
new_page_title = repPl.title()
@@ -817,8 +815,8 @@
newlink = "[[%s%s]]%s" % (new_page_title,
section,
trailing_chars)
- elif replaceit or (new_page_title == link_text
- and not section):
+ elif replaceit or (new_page_title == link_text and
+ not section):
newlink = "[[%s]]" % new_page_title
# check if we can create a link with trailing characters
# instead of a pipelink
@@ -856,8 +854,8 @@
def findAlternatives(self, disambPage):
if disambPage.isRedirectPage() and not self.primary:
- if (disambPage.site.lang in self.primary_redir_template
- and self.primary_redir_template[disambPage.site.lang]
+ if (disambPage.site.lang in self.primary_redir_template and
+ self.primary_redir_template[disambPage.site.lang]
in disambPage.templates(get_redirect=True)):
baseTerm = disambPage.title()
for template in disambPage.templatesWithParams(
diff --git a/scripts/transferbot.py b/scripts/transferbot.py
index 599bc91..8b9cbcf 100644
--- a/scripts/transferbot.py
+++ b/scripts/transferbot.py
@@ -134,8 +134,7 @@
for page in gen:
summary = "Moved page from %s" % page.title(asLink=True)
targetpage = pywikibot.Page(tosite, prefix + page.title())
- edithistpage = pywikibot.Page(tosite, prefix + page.title()
- + "/edithistory")
+ edithistpage = pywikibot.Page(tosite, prefix + page.title() + '/edithistory')
if targetpage.exists() and not overwrite:
pywikibot.output(
diff --git a/scripts/unlink.py b/scripts/unlink.py
index de05fdd..403d626 100755
--- a/scripts/unlink.py
+++ b/scripts/unlink.py
@@ -99,9 +99,9 @@
choice = 'a'
else:
pywikibot.output(
- text[max(0, match.start() - context):match.start()]
- + '\03{lightred}' + text[match.start():match.end()]
- + '\03{default}' + text[match.end():match.end() + context])
+ text[max(0, match.start() - context):match.start()] +
+ '\03{lightred}' + text[match.start():match.end()] +
+ '\03{default}' + text[match.end():match.end() + context])
choice = pywikibot.input_choice(
u'\nWhat shall be done with this link?\n',
[('unlink', 'u'), ('skip', 's'), ('edit', 'e'),
diff --git a/tests/__init__.py b/tests/__init__.py
index 0f8012a..556162f 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -102,13 +102,13 @@
"""List tests which are to be executed."""
dir_list = os.listdir(_tests_dir)
all_test_list = [name[0:-9] for name in dir_list # strip '_tests.py'
- if name.endswith('_tests.py')
- and not name.startswith('_')] # skip __init__.py and _*
+ if name.endswith('_tests.py') and
+ not name.startswith('_')] # skip __init__.py and _*
unknown_test_modules = [name
for name in all_test_list
- if name not in library_test_modules
- and name not in script_test_modules]
+ if name not in library_test_modules and
+ name not in script_test_modules]
return unknown_test_modules
diff --git a/tests/aspects.py b/tests/aspects.py
index 8147a70..250ffb2 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -687,9 +687,9 @@
if 'family' in dct or 'code' in dct:
dct['site'] = True
- if (('sites' not in dct or not len(dct['sites']))
- and 'family' in dct
- and 'code' in dct and dct['code'] != '*'):
+ if (('sites' not in dct or not len(dct['sites'])) and
+ 'family' in dct and
+ 'code' in dct and dct['code'] != '*'):
# Add entry to self.sites
dct['sites'] = {
str(dct['family'] + ':' + dct['code']): {
diff --git a/tests/script_tests.py b/tests/script_tests.py
index 6810a00..aea9dcc 100644
--- a/tests/script_tests.py
+++ b/tests/script_tests.py
@@ -68,9 +68,9 @@
script_list = (['login'] +
[name[0:-3] for name in os.listdir(scripts_path) # strip '.py'
- if name.endswith('.py')
- and not name.startswith('_') # skip __init__.py and _*
- and name != 'login.py' # this is moved to be first
+ if name.endswith('.py') and
+ not name.startswith('_') and # skip __init__.py and _*
+ name != 'login.py' # this is moved to be first
]
)
@@ -181,17 +181,17 @@
tests = (['test__login_help'] +
['test_' + name + '_help'
for name in sorted(script_list)
- if name != 'login'
- and name not in deadlock_script_list] +
+ if name != 'login' and
+ name not in deadlock_script_list] +
['test__login_simulate'])
tests += ['test_' + name + '_simulate'
for name in sorted(script_list)
- if name != 'login'
- and name not in deadlock_script_list
- and name not in failed_dep_script_list
- and name not in unrunnable_script_list
- and (enable_autorun_tests or name not in auto_run_script_list)]
+ if name != 'login' and
+ name not in deadlock_script_list and
+ name not in failed_dep_script_list and
+ name not in unrunnable_script_list and
+ (enable_autorun_tests or name not in auto_run_script_list)]
test_list = ['tests.script_tests.TestScript.' + name
for name in tests]
@@ -285,8 +285,8 @@
# But also complain if there is any stdout
# but ignore shell.py emiting its '>>> ' prompt.
if ((script_name == 'shell' and
- set(result['stdout']).issubset(set('> \n')))
- or result['stdout'] == ''):
+ set(result['stdout']).issubset(set('> \n'))) or
+ result['stdout'] == ''):
result['stdout'] = None
self.assertIsNone(result['stdout'])
diff --git a/tests/site_tests.py b/tests/site_tests.py
index b62bba7..b3ac597 100644
--- a/tests/site_tests.py
+++ b/tests/site_tests.py
@@ -971,8 +971,7 @@
self.assertLessEqual(len(uc), 10)
self.assertTrue(all(isinstance(contrib, dict)
for contrib in uc))
- self.assertTrue(all("user" in contrib
- and contrib["user"] == mysite.user()
+ self.assertTrue(all('user' in contrib and contrib['user'] == mysite.user()
for contrib in uc))
for contrib in mysite.usercontribs(userprefix="John", total=5):
self.assertIsInstance(contrib, dict)
--
To view, visit https://gerrit.wikimedia.org/r/190753
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I5d89afa1d7bd4711a80d8b6c831ee63afe440ef5
Gerrit-PatchSet: 2
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Minor documentation fixes
......................................................................
Minor documentation fixes
Change-Id: Idde50d76be2cbf05a6075c9ff39fdbb5a029bee4
---
M pywikibot/userinterfaces/win32_unicode.py
1 file changed, 3 insertions(+), 3 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/userinterfaces/win32_unicode.py b/pywikibot/userinterfaces/win32_unicode.py
index 9e4dded..64016f7 100755
--- a/pywikibot/userinterfaces/win32_unicode.py
+++ b/pywikibot/userinterfaces/win32_unicode.py
@@ -1,7 +1,7 @@
"""Stdout, stderr and argv support for unicode."""
##############################################
# Support for unicode in windows cmd.exe
-# Posted on Stack Overflow [1], available under CC-BY-SA [2]
+# Posted on Stack Overflow [1], available under CC-BY-SA 3.0 [2]
#
# Question: "Windows cmd encoding change causes Python crash" [3] by Alex [4],
# Answered [5] by David-Sarah Hopwood [6].
@@ -15,8 +15,8 @@
#
################################################
#
-# stdin support added by Merlijn van Deen <valhallasw(a)gmail.com>, march 2012
-# Licensed under both CC-BY-SA as the MIT license.
+# stdin support added by Merlijn van Deen <valhallasw(a)gmail.com>, March 2012
+# Licensed under both CC-BY-SA and the MIT license.
#
################################################
from __future__ import print_function
--
To view, visit https://gerrit.wikimedia.org/r/190716
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Idde50d76be2cbf05a6075c9ff39fdbb5a029bee4
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [FEAT] Site: blockuser's expiry supports datetime and False
......................................................................
[FEAT] Site: blockuser's expiry supports datetime and False
As it already support timestamps the addition of normal datetimes is not
that far fetched. It also supports 'False' as an alias for 'never' so
scripts are independent of the API and only pywikibot needs to use the
actual API value.
This also adds the documentation for this function.
Change-Id: I352d155cea0d251f35d27e887bbc84e6ee83d549
---
M pywikibot/site.py
1 file changed, 33 insertions(+), 0 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index c4cd53d..626a8ee 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -4396,8 +4396,41 @@
@must_be(group='sysop')
def blockuser(self, user, expiry, reason, anononly=True, nocreate=True,
autoblock=True, noemail=False, reblock=False):
+ """
+ Block a user for certain amount of time and for a certain reason.
+ @param user: The username/IP to be blocked without a namespace.
+ @type user: User
+ @param expiry: The length or date/time when the block expires. If
+ 'never', 'infinite', 'indefinite' it never does. If the value is
+ given as a basestring it's parsed by php's strtotime function:
+ http://php.net/manual/en/function.strtotime.php
+ The relative format is described there:
+ http://php.net/manual/en/datetime.formats.relative.php
+ It is recommended to not use a basestring if possible to be
+ independent of the API.
+ @type expiry: Timestamp/datetime (absolute),
+ basestring (relative/absolute) or False ('never')
+ @param reason: The reason for the block.
+ @type reason: basestring
+ @param anononly: Disable anonymous edits for this IP.
+ @type anononly: boolean
+ @param nocreate: Prevent account creation.
+ @type nocreate: boolean
+ @param autoblock: Automatically block the last used IP address and all
+ subsequent IP addresses from which this account logs in.
+ @type autoblock: boolean
+ @param noemail: Prevent user from sending email through the wiki.
+ @type noemail: boolean
+ @param reblock: If the user is already blocked, overwrite the existing
+ block.
+ @type reblock: boolean
+ @return: The data retrieved from the API request.
+ @rtype: dict
+ """
token = self.tokens['block']
+ if expiry is False:
+ expiry = 'never'
req = api.Request(site=self, action='block', user=user.username,
expiry=expiry, reason=reason, token=token)
if anononly:
--
To view, visit https://gerrit.wikimedia.org/r/181082
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I352d155cea0d251f35d27e887bbc84e6ee83d549
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: tools.py: introduce class DotReadableDict(), super of Revision() and FileInfo()
......................................................................
tools.py: introduce class DotReadableDict(), super of Revision() and FileInfo()
Parent class of Page.Revision() and Page.FileInfo().
Provide:
- __getitem__()
- __unicode__()
-__repr__().
Change-Id: I45877492693837da4f53f11f9869a52dea25c3b0
---
M pywikibot/page.py
M pywikibot/tools.py
2 files changed, 38 insertions(+), 38 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index bb1f515..1befe68 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -48,6 +48,7 @@
SiteDefinitionError
)
from pywikibot.tools import (
+ UnicodeMixin, DotReadableDict,
ComparableMixin, deprecated, deprecate_arg, deprecated_args,
remove_last_args, _NotImplementedWarning,
OrderedDict, Counter,
@@ -64,7 +65,7 @@
# Note: Link objects (defined later on) represent a wiki-page's title, while
# Page objects (defined here) represent the page itself, including its contents.
-class BasePage(pywikibot.UnicodeMixin, ComparableMixin):
+class BasePage(UnicodeMixin, ComparableMixin):
"""BasePage: Base object for a MediaWiki page.
@@ -4210,7 +4211,7 @@
}
-class Revision(pywikibot.UnicodeMixin):
+class Revision(DotReadableDict):
"""A structure holding information about a single revision of a Page."""
@@ -4268,29 +4269,8 @@
return Revision.FullHistEntry(self.revid, self.timestamp, self.user,
self.text, self.rollbacktoken)
- def __getitem__(self, key):
- """Give access to Revision class values by key.
- Revision class may also give access to its values by keys
- e.g. revid parameter may be assigned by revision['revid']
- as well as revision.revid. This makes formatting strings with
- % operator easier.
-
- """
- return getattr(self, key)
-
- def __unicode__(self):
- """Return string representation."""
- _content = u', '.join(
- u'{0}: {1}'.format(k, v) for k, v in self.__dict__.items())
- return u'{{{0}}}'.format(_content)
-
- def __repr__(self):
- """Return a more complete string representation."""
- return self.__dict__.__repr__()
-
-
-class FileInfo(pywikibot.UnicodeMixin):
+class FileInfo(DotReadableDict):
"""A structure holding imageinfo of latest rev. of FilePage.
@@ -4316,23 +4296,9 @@
self.__dict__.update(file_revision)
self.timestamp = pywikibot.Timestamp.fromISOformat(self.timestamp)
- def __getitem__(self, key):
- """Access attributes also with dict.like keys."""
- return getattr(self, key)
-
def __eq__(self, other):
"""Test if two File_info objects are equal."""
return self.__dict__ == other.__dict__
-
- def __unicode__(self):
- """Return string representation."""
- _content = u', '.join(
- u'{0}: {1}'.format(k, v) for k, v in self.__dict__.items())
- return u'{{{0}}}'.format(_content)
-
- def __repr__(self):
- """Return a more complete string representation."""
- return self.__dict__.__repr__()
class Link(ComparableMixin):
diff --git a/pywikibot/tools.py b/pywikibot/tools.py
index dd5ec2c..cb19499 100644
--- a/pywikibot/tools.py
+++ b/pywikibot/tools.py
@@ -136,6 +136,40 @@
return other != self._cmpkey()
+class DotReadableDict(UnicodeMixin):
+
+ """Parent class of Revision() and FileInfo().
+
+ Provide:
+ - __getitem__(), __unicode__() and __repr__().
+
+ """
+
+ def __getitem__(self, key):
+ """Give access to class values by key.
+
+ Revision class may also give access to its values by keys
+ e.g. revid parameter may be assigned by revision['revid']
+ as well as revision.revid. This makes formatting strings with
+ % operator easier.
+
+ """
+ return getattr(self, key)
+
+ def __unicode__(self):
+ """Return string representation."""
+ if sys.version_info[0] > 2:
+ return repr(self.__dict__)
+ else:
+ _content = u', '.join(
+ u'{0}: {1}'.format(k, v) for k, v in self.__dict__.items())
+ return u'{{{0}}}'.format(_content)
+
+ def __repr__(self):
+ """Return a more complete string representation."""
+ return repr(self.__dict___)
+
+
def concat_options(message, line_length, options):
"""Concatenate options."""
indent = len(message) + 2
--
To view, visit https://gerrit.wikimedia.org/r/190563
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I45877492693837da4f53f11f9869a52dea25c3b0
Gerrit-PatchSet: 2
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: Ricordisamoa <ricordisamoa(a)openmailbox.org>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Enable edit failure tests in travis builds
......................................................................
Enable edit failure tests in travis builds
Adds new environment variable PYWIKIBOT2_TEST_WRITE_FAIL
which when set to '1' will run edit failure tests, which are
much safer than the other 'write' tests.
Also improve documentation for travis builds.
Change-Id: I85bf198c2a30b69a9e29d220d8696a92642272bc
---
M .travis.yml
M tests/README.rst
M tests/aspects.py
M tests/edit_failure_tests.py
4 files changed, 67 insertions(+), 21 deletions(-)
Approvals:
John Vandenberg: Looks good to me, but someone else must approve
XZise: Looks good to me, approved
jenkins-bot: Verified
diff --git a/.travis.yml b/.travis.yml
index f0c970b..1233f57 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -32,15 +32,20 @@
- echo "maximum_GET_length = 5000" >> ~/.pywikibot/user-config.py
- echo "console_encoding = 'utf8'" >> ~/.pywikibot/user-config.py
- - if [[ "$GITHUB_USER" == "wikimedia" ]]; then PYWIKIBOT2_USERNAME="Pywikibot-test"; fi
+ - if [[ "$GITHUB_USER" == "wikimedia" ]]; then
+ PYWIKIBOT2_USERNAME="Pywikibot-test" ;
+ else
+ export PYWIKIBOT2_TEST_WRITE_FAIL=1 ;
+ fi
- - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then echo "usernames['$FAMILY']['$LANGUAGE'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py; fi
- - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then echo "usernames['wikipedia']['en'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py; fi
- - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then echo "usernames['wikipedia']['test'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py; fi
- - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then echo "usernames['wikidata']['test'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py; fi
- - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then echo "usernames['commons']['commons'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py; fi
-
- - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then echo "('$PYWIKIBOT2_USERNAME', '$USER_PASSWORD')" > ~/.pywikibot/passwordfile; fi
+ - if [[ -n "$USER_PASSWORD" && -n "$PYWIKIBOT2_USERNAME" ]]; then
+ echo "usernames['$FAMILY']['$LANGUAGE'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py ;
+ echo "usernames['wikipedia']['en'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py ;
+ echo "usernames['wikipedia']['test'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py ;
+ echo "usernames['wikidata']['test'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py ;
+ echo "usernames['commons']['commons'] = '$PYWIKIBOT2_USERNAME'" >> ~/.pywikibot/user-config.py ;
+ echo "('$PYWIKIBOT2_USERNAME', '$USER_PASSWORD')" > ~/.pywikibot/passwordfile ;
+ fi
- cd externals/httplib2
- python setup.py install
diff --git a/tests/README.rst b/tests/README.rst
index 4258016..214c110 100644
--- a/tests/README.rst
+++ b/tests/README.rst
@@ -83,7 +83,7 @@
use the Wikimedia global (SUL) account 'Pywikibot-test', which has a password
securely stored in .travis.yml . See section env:global:secure.
-Anyone can run these tests on travis-ci.org using their own account, with
+Anyone can run these tests on travis-ci.org using their own github account, with
code changes that have not been merged into the main repository. To do this:
1. create a github and travis-ci account
@@ -103,9 +103,35 @@
2. Add a new variable named PYWIKIBOT2_USERNAME and a value of a valid
Wikimedia SUL username
3. Add another variable named USER_PASSWORD, with the private password for
- the Wikimedia SUL username used in step 2
+ the Wikimedia SUL username used in step 2. Check that this
+ environment variable has "Display value in build logs" set to OFF, so
+ the password does not leak into the build logs.
4. The next build should run tests that require a logged in user
+While passwords in travis-ci environment variables are not leaked in normal
+operations, you are responsible for your own passwords.
+
+It is strongly recommended that an untrusted bot account is created for
+travis tests, using a password that is not shared with trusted accounts.
+
+There are a set of 'edit failure' tests, which attempt to write to the wikis
+and **should** fail. If there is a bug in pywikibot or MediaWiki, these
+tests **may** actually perform a write operation.
+
+These 'edit failure' tests are disabled by default for the 'wikimedia' builds,
+but are enabled by default on builds by any other github account.
+
+To disable 'edit failure' tests in travis, add PYWIKIBOT2_TEST_WRITE_FAIL=0
+
+There are also several other 'write' tests which also attempt to perform
+write operations successfully. These **will** write to the wikis, and they
+should always only write to 'test' wikis.
+
+These 'write' tests are disabled in travis builds, and currently can not be
+run on travis as they require interaction using a terminal.
+
+To enable 'write' tests in travis, add PYWIKIBOT2_TEST_WRITE=1
+
Contributing tests
==================
diff --git a/tests/aspects.py b/tests/aspects.py
index be21cf8..8147a70 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -518,24 +518,37 @@
"""
Set up the test class.
- Prevent test classes to write to the site and also cache results.
+ Reject write test classes configured with non-test wikis, or caching.
- Skip the test class if environment variable PYWIKIBOT2_TEST_WRITE
- does not equal 1.
+ Prevent test classes from writing to the site by default.
+
+ If class attribute 'write' is -1, the test class is skipped unless
+ environment variable PYWIKIBOT2_TEST_WRITE_FAIL is set to 1.
+
+ Otherwise the test class is skipped unless environment variable
+ PYWIKIBOT2_TEST_WRITE is set to 1.
"""
- if os.environ.get('PYWIKIBOT2_TEST_WRITE', '0') != '1':
+ super(SiteWriteMixin, cls).setUpClass()
+
+ site = cls.get_site()
+ assert('test' in (site.family.name, site.code))
+
+ if cls.write == -1:
+ env_var = 'PYWIKIBOT2_TEST_WRITE_FAIL'
+ else:
+ env_var = 'PYWIKIBOT2_TEST_WRITE'
+
+ if os.environ.get(env_var, '0') != '1':
raise unittest.SkipTest(
'%r write tests disabled. '
- 'Set PYWIKIBOT2_TEST_WRITE=1 to enable.'
- % cls.__name__)
+ 'Set %s=1 to enable.'
+ % (cls.__name__, env_var))
if issubclass(cls, ForceCacheMixin):
raise Exception(
'%s can not be a subclass of both '
'SiteEditTestCase and ForceCacheMixin'
% cls.__name__)
-
- super(SiteWriteMixin, cls).setUpClass()
class RequireUserMixin(TestCaseBase):
diff --git a/tests/edit_failure_tests.py b/tests/edit_failure_tests.py
index 57d3ffd..fa3c1db 100644
--- a/tests/edit_failure_tests.py
+++ b/tests/edit_failure_tests.py
@@ -4,6 +4,8 @@
These tests should never write to the wiki,
unless something has broken badly.
+
+These tests use special code 'write = -1' for edit failures.
"""
#
# (C) Pywikibot team, 2014
@@ -27,7 +29,7 @@
"""Test cases for edits which should fail to save."""
- write = True
+ write = -1
family = 'wikipedia'
code = 'test'
@@ -55,7 +57,7 @@
"""Test cases for actions which should fail to save."""
- write = True
+ write = -1
family = 'wikipedia'
code = 'test'
@@ -87,7 +89,7 @@
family = 'wikidata'
code = 'test'
- write = True
+ write = -1
def test_itempage_save(self):
"""Test ItemPage save method inherited from superclass Page."""
--
To view, visit https://gerrit.wikimedia.org/r/190635
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I85bf198c2a30b69a9e29d220d8696a92642272bc
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Normalize usernames in password file
......................................................................
Normalize usernames in password file
Capitalize the first letter of username in password file when used according to
Wikipedia username policy. Warn if the format of tuple in password file is not
correct.
Bug: T74974
Change-Id: I2035bf03bad62f6f505b2a9129758c2cc4f6b5ce
---
M pywikibot/exceptions.py
M pywikibot/login.py
2 files changed, 27 insertions(+), 5 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index 3bb6a7a..2a8105f 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -57,6 +57,7 @@
UserWarning: warnings targetted at users
- config2._ConfigurationDeprecationWarning: user configuration file problems
+ - login._PasswordFileWarning: password file problems
- ArgumentDeprecationWarning: command line argument problems
- FamilyMaintenanceWarning: missing information in family definition
"""
diff --git a/pywikibot/login.py b/pywikibot/login.py
index db7be8f..816378f 100644
--- a/pywikibot/login.py
+++ b/pywikibot/login.py
@@ -3,18 +3,27 @@
"""Library to log the bot in to a wiki account."""
#
# (C) Rob W.W. Hooft, 2003
-# (C) Pywikibot team, 2003-2012
+# (C) Pywikibot team, 2003-2015
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
#
import codecs
+from warnings import warn
import pywikibot
from pywikibot import config
from pywikibot.tools import deprecated_args
from pywikibot.exceptions import NoUsername
+
+
+class _PasswordFileWarning(UserWarning):
+
+ """The format of password file is incorrect."""
+
+ pass
+
_logger = "wiki.login"
@@ -169,18 +178,30 @@
for line in password_f:
if not line.strip():
continue
- entry = eval(line)
+ try:
+ entry = eval(line)
+ except SyntaxError:
+ entry = None
+ if type(entry) is not tuple:
+ warn('Invalid tuple', _PasswordFileWarning)
+ continue
+ if not 2 <= len(entry) <= 4:
+ warn('The length of tuple should be 2 to 4 (%s given)'
+ % len(entry), _PasswordFileWarning)
+ continue
+ username = entry[-2]
+ username = username[0].upper() + username[1:]
if len(entry) == 4: # for userinfo included code and family
if entry[0] == self.site.code and \
entry[1] == self.site.family.name and \
- entry[2] == self.username:
+ username == self.username:
self.password = entry[3]
elif len(entry) == 3: # for userinfo included family
if entry[0] == self.site.family.name and \
- entry[1] == self.username:
+ username == self.username:
self.password = entry[2]
elif len(entry) == 2: # for default userinfo
- if entry[0] == self.username:
+ if username == self.username:
self.password = entry[1]
password_f.close()
--
To view, visit https://gerrit.wikimedia.org/r/190638
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I2035bf03bad62f6f505b2a9129758c2cc4f6b5ce
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: VcamX <vcamx3(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: VcamX <vcamx3(a)gmail.com>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [FIX] Upload: Fixing uploads
......................................................................
[FIX] Upload: Fixing uploads
When there is a page name problem, it reports it and it might then exit
the loop. But if there is no problem it doesn't continue but asks the
user and the loop continues.
It also calls upload_file internally and thus preserving forwarding the
URL, as upload_image was assuming all URLs are a string.
Change-Id: I0020e214db1cf0e276d9267c94d49859802b0a6e
---
M scripts/upload.py
1 file changed, 6 insertions(+), 4 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/scripts/upload.py b/scripts/upload.py
index b02068b..ba258b3 100755
--- a/scripts/upload.py
+++ b/scripts/upload.py
@@ -6,7 +6,7 @@
Arguments:
-keep Keep the filename as is
- -filename Target filename
+ -filename Target filename without the namespace prefix
-noverify Do not ask for verification of the upload description if one
is given
-abortonwarn: Abort upload on the specified warning type. If no warning type
@@ -229,8 +229,8 @@
first_check = True
while True:
if not first_check:
- filename = pywikibot.input(u'Enter a better name, '
- 'or press enter to skip:')
+ filename = pywikibot.input('Enter a better name, or press '
+ 'enter to skip the file:')
if not filename:
return None
first_check = False
@@ -270,6 +270,8 @@
"repository and cannot be overwritten."
% filename)
continue
+ else:
+ break
except pywikibot.NoPage:
break
@@ -372,7 +374,7 @@
if answer:
self.ignoreWarning = True
self.keepFilename = True
- return self.upload_image(debug)
+ return self.upload_file(file_url, debug)
else:
pywikibot.output(u"Upload aborted.")
return
--
To view, visit https://gerrit.wikimedia.org/r/190560
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I0020e214db1cf0e276d9267c94d49859802b0a6e
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: jenkins-bot <>
Build Update for wikimedia/pywikibot-core
-------------------------------------
Build: #1985
Status: Fixed
Duration: 47 minutes and 39 seconds
Commit: 464bd24 (master)
Author: John Vandenberg
Message: Move import of 'gui' to top of file
Using 'import foo.bar.x' in the middle of function defines 'foo'
in that context, and if the import fails 'foo' is no longer bound.
Bug: T89485
Change-Id: Ic43af9d08dd5c4e006ebfb12f03dd90ae7ec5423
View the changeset: https://github.com/wikimedia/pywikibot-core/compare/5e895f8e41fe...464bd248…
View the full build log and details: https://travis-ci.org/wikimedia/pywikibot-core/builds/50696783
--
You can configure recipients for build notifications in your .travis.yml file. See http://docs.travis-ci.com/user/notifications
jenkins-bot has submitted this change and it was merged.
Change subject: Move import of 'gui' to top of file
......................................................................
Move import of 'gui' to top of file
Using 'import foo.bar.x' in the middle of function defines 'foo'
in that context, and if the import fails 'foo' is no longer bound.
Bug: T89485
Change-Id: Ic43af9d08dd5c4e006ebfb12f03dd90ae7ec5423
---
M pywikibot/editor.py
1 file changed, 8 insertions(+), 4 deletions(-)
Approvals:
Merlijn van Deen: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/editor.py b/pywikibot/editor.py
index 32afdc6..7d1687d 100644
--- a/pywikibot/editor.py
+++ b/pywikibot/editor.py
@@ -17,8 +17,14 @@
import tempfile
import pywikibot
+
from pywikibot import config
from pywikibot.tools import deprecated
+
+try:
+ from pywikibot.userinterfaces import gui # noqa
+except ImportError as e:
+ gui = e
class TextEditor(object):
@@ -107,14 +113,12 @@
finally:
os.unlink(tempFilename)
- try:
- import pywikibot.userinterfaces.gui # noqa
- except ImportError as e:
+ if isinstance(gui, ImportError):
raise pywikibot.Error(
'Could not load GUI modules: %s\nNo editor available.\n'
'Set your favourite editor in user-config.py "editor", '
'or install python packages tkinter and idlelib, which '
'are typically part of Python but may be packaged separately '
- 'on your platform.\n' % e)
+ 'on your platform.\n' % gui)
return pywikibot.ui.editText(text, jumpIndex=jumpIndex, highlight=highlight)
--
To view, visit https://gerrit.wikimedia.org/r/190561
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ic43af9d08dd5c4e006ebfb12f03dd90ae7ec5423
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [FEAT] Category: Get newest pages
......................................................................
[FEAT] Category: Get newest pages
This returns the pages which have been added to a category ordered by
the creation date from newest to oldest. To do that it needs to cache
all pages and check on each iteration if any previously cached page was
created after the current page is added. If that is the case the cached
pages are newer than the current page and any other page which will be
checked as the generator progresses as they are ordered by addition to
the category and only pages are returned which were added to the
category before the current page was added.
Change-Id: I9bb3f74bbe2e3319ed2dbcdefab414a3204c2c32
---
M pywikibot/page.py
M tests/category_tests.py
2 files changed, 90 insertions(+), 0 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index c63af01..61e1d1b 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -2439,6 +2439,74 @@
"""
return self.site.categoryinfo(self)
+ def newest_pages(self, total=None):
+ """
+ Return pages in a category ordered by the creation date.
+
+ If two or more pages are created at the same time, the pages are
+ returned in the order they were added to the category. The most recently
+ added page is returned first.
+
+ It only allows to return the pages ordered from newest to oldest, as it
+ is impossible to determine the oldest page in a category without
+ checking all pages. But it is possible to check the category in order
+ with the newly added first and it yields all pages which were created
+ after the currently checked page was added (and thus there is no page
+ created after any of the cached but added before the currently checked).
+
+ @param total: The total number of pages queried.
+ @type total: int
+ @return: A page generator of all pages in a category ordered by the
+ creation date. From newest to oldest. Note: It currently only
+ returns Page instances and not a subclass of it if possible. This
+ might change so don't expect to only get Page instances.
+ @rtype: generator
+ """
+ def check_cache(latest):
+ """Return the cached pages in order and not more than total."""
+ cached = []
+ for timestamp in sorted((ts for ts in cache if ts > latest),
+ reverse=True):
+ # The complete list can be removed, it'll either yield all of
+ # them, or only a portion but will skip the rest anyway
+ cached += cache.pop(timestamp)[:None if total is None else
+ total - len(cached)]
+ if total and len(cached) >= total:
+ break # already got enough
+ assert(total is None or len(cached) <= total)
+ return cached
+
+ # all pages which have been checked but where created before the
+ # current page was added, at some point they will be created after
+ # the current page was added. It saves all pages via the creation
+ # timestamp. Be prepared for multiple pages.
+ cache = defaultdict(list)
+ # TODO: Make site.categorymembers is usable as it returns pages
+ # There is no total defined, as it's not known how many pages need to be
+ # checked before the total amount of new pages was found. In worst case
+ # all pages of a category need to be checked.
+ for member in pywikibot.data.api.QueryGenerator(
+ site=self.site, list='categorymembers', cmsort='timestamp',
+ cmdir='older', cmprop='timestamp|title',
+ cmtitle=self.title()):
+ # TODO: Upcast to suitable class
+ page = pywikibot.Page(self.site, member['title'])
+ assert(page.namespace() == member['ns'])
+ cached = check_cache(pywikibot.Timestamp.fromISOformat(
+ member['timestamp']))
+ for cached_page in cached:
+ yield cached_page
+ if total is not None:
+ total -= len(cached)
+ if total <= 0:
+ break
+ cache[page.oldest_revision.timestamp] += [page]
+ else:
+ # clear cache
+ assert(total is None or total > 0)
+ for cached_page in check_cache(pywikibot.Timestamp.min):
+ yield cached_page
+
# ### DEPRECATED METHODS ####
@deprecated("list(Category.subcategories(...))")
def subcategoriesList(self, recurse=False):
diff --git a/tests/category_tests.py b/tests/category_tests.py
index 8923884..d9d543c 100644
--- a/tests/category_tests.py
+++ b/tests/category_tests.py
@@ -209,6 +209,28 @@
self.assertEqual(cat.aslink(sortKey='Foo'), '[[Category:Wikipedia categories|Foo]]')
+class CategoryNewestPages(TestCase):
+
+ """Test newest_pages feature on French Wikinews."""
+
+ family = 'wikinews'
+ code = 'fr'
+
+ cached = True
+
+ def test_newest_pages(self):
+ """Test that the pages are getting older."""
+ cat = pywikibot.Category(self.get_site(), u'Catégorie:Yukon Quest 2015')
+ last = pywikibot.Timestamp.max
+ count = 0
+ for page in cat.newest_pages():
+ creation_stamp = page.oldest_revision.timestamp
+ self.assertLessEqual(creation_stamp, last)
+ last = creation_stamp
+ count += 1
+ self.assertEqual(count, cat.categoryinfo['size'])
+
+
if __name__ == '__main__':
try:
unittest.main()
--
To view, visit https://gerrit.wikimedia.org/r/190137
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I9bb3f74bbe2e3319ed2dbcdefab414a3204c2c32
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [bugfix] Extract pathname for python 2.7 too
......................................................................
[bugfix] Extract pathname for python 2.7 too
Solves unexprected AssertionError in bot.py
Bug: T89233
Change-Id: I07d55ba7082f54990f7ee33b48fca30a3776428d
---
M pywikibot/bot.py
1 file changed, 3 insertions(+), 3 deletions(-)
Approvals:
John Vandenberg: Verified; Looks good to me, approved
Xqt: Verified
jenkins-bot: Verified
diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index e255580..22e614f 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -107,13 +107,13 @@
"""Strip trailing newlines before outputting text to file."""
# Warnings captured from the warnings system are not processed by
# logoutput(), so the 'context' variables are missing.
- # The same context details are provided by Python 2.7, but need to
- # be extracted from the warning message for Python 2.6.
+ # The same context details are provided by Python 3.X, but need to
+ # be extracted from the warning message for Python <= 2.7.
if record.name == 'py.warnings' and 'caller_file' not in record.__dict__:
assert(len(record.args) == 1)
msg = record.args[0]
- if sys.version_info < (2, 7):
+ if sys.version_info[0] < 3:
record.pathname = msg.partition(':')[0]
record.lineno = msg.partition(':')[2].partition(':')[0]
record.module = msg.rpartition('/')[2].rpartition('.')[0]
--
To view, visit https://gerrit.wikimedia.org/r/189944
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I07d55ba7082f54990f7ee33b48fca30a3776428d
Gerrit-PatchSet: 3
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Do not change pipe links with r# choice
......................................................................
Do not change pipe links with r# choice
When there is a pipe link, r# as well as # choice options
shouldn't change it. # should always create a pipe link if there
isn't one (which is the given behaviour). But #r should not replace
an already given pipe link with the new target link only but keep
the link text.
Change-Id: I54cc7beec8d9a2037b28d4763dd57a44823fa457
---
M scripts/solve_disambiguation.py
1 file changed, 1 insertion(+), 1 deletion(-)
Approvals:
John Vandenberg: Looks good to me, approved
Xqt: Looks good to me, but someone else must approve
jenkins-bot: Verified
diff --git a/scripts/solve_disambiguation.py b/scripts/solve_disambiguation.py
index f25f617..0248094 100644
--- a/scripts/solve_disambiguation.py
+++ b/scripts/solve_disambiguation.py
@@ -776,7 +776,7 @@
else:
if len(choice) > 0 and choice[0] == 'r':
# we want to throw away the original link text
- replaceit = True
+ replaceit = link_text == page_title
choice = choice[1:]
elif include == "redirect":
replaceit = True
--
To view, visit https://gerrit.wikimedia.org/r/176477
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I54cc7beec8d9a2037b28d4763dd57a44823fa457
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Ricordisamoa <ricordisamoa(a)openmailbox.org>
Gerrit-Reviewer: Russell Blau <russblau(a)imapmail.org>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Enabling the error handling in decode method.
......................................................................
Enabling the error handling in decode method.
Enabled python implementation of error handling for the decode method of
HttpRequest. It accepts the "errors" argument which can
take the values like 'strict', 'replace' and 'ignore' according to need.
'strict' is the default value.
Bug: T88928
Change-Id: I02609a5abcdf0e5e66bbb4ffdcc41aaf74d5c943
---
M pywikibot/comms/threadedhttp.py
1 file changed, 2 insertions(+), 2 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
XZise: Looks good to me, but someone else must approve
jenkins-bot: Verified
diff --git a/pywikibot/comms/threadedhttp.py b/pywikibot/comms/threadedhttp.py
index b7a7422..a2f6ef3 100644
--- a/pywikibot/comms/threadedhttp.py
+++ b/pywikibot/comms/threadedhttp.py
@@ -477,9 +477,9 @@
raise self._encoding
return self._encoding
- def decode(self, encoding):
+ def decode(self, encoding, errors='strict'):
"""Return the decoded response."""
- return self.raw.decode(self.encoding)
+ return self.raw.decode(encoding, errors)
@property
def content(self):
--
To view, visit https://gerrit.wikimedia.org/r/189975
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I02609a5abcdf0e5e66bbb4ffdcc41aaf74d5c943
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Maverick <manpreetkaur9411(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: category.py breaks articles with includeonly and noinclude
......................................................................
category.py breaks articles with includeonly and noinclude
Note:
New lines are inserted around new cat by category.py.
Such behaviour has not been changed in spite of the bug description.
Bug: T57315
Change-Id: I06f59da44c8216a9b2a2619bf7c1d210c06b23f5
---
M pywikibot/textlib.py
1 file changed, 1 insertion(+), 1 deletion(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py
index 530dc70..407041b 100644
--- a/pywikibot/textlib.py
+++ b/pywikibot/textlib.py
@@ -733,7 +733,7 @@
catNamespace = '|'.join(site.category_namespaces())
categoryR = re.compile(r'\[\[\s*(%s)\s*:.*?\]\]\s*' % catNamespace, re.I)
text = replaceExcept(text, categoryR, '',
- ['nowiki', 'comment', 'math', 'pre', 'source'],
+ ['nowiki', 'comment', 'math', 'pre', 'source', 'includeonly'],
marker=marker,
site=site)
if marker:
--
To view, visit https://gerrit.wikimedia.org/r/89026
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I06f59da44c8216a9b2a2619bf7c1d210c06b23f5
Gerrit-PatchSet: 3
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Port getFirstUploader to core. For compatibility with compat only.
......................................................................
Port getFirstUploader to core. For compatibility with compat only.
Change-Id: Iaa9848d7020f994e090fbae3356a1a661239e904
---
M pywikibot/page.py
1 file changed, 9 insertions(+), 0 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
XZise: Looks good to me, but someone else must approve
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 1c318df..3e0dfb7 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -2095,6 +2095,15 @@
"""Return the file's SHA1 checksum."""
return self.latest_file_info.sha1
+ @deprecated("FilePage.oldest_file_info.user")
+ def getFirstUploader(self):
+ """Return a list with first uploader of the FilePage and timestamp.
+
+ For compatibility with compat only.
+
+ """
+ return [self.oldest_file_info.user, self.oldest_file_info.timestamp]
+
@deprecated("FilePage.latest_file_info.user")
def getLatestUploader(self):
"""Return a list with latest uploader of the FilePage and timestamp.
--
To view, visit https://gerrit.wikimedia.org/r/189012
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Iaa9848d7020f994e090fbae3356a1a661239e904
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Legoktm <legoktm.wikipedia(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: Ricordisamoa <ricordisamoa(a)openmailbox.org>
Gerrit-Reviewer: Russell Blau <russblau(a)imapmail.org>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: [IMPROV] Remove spaces between """ and it's text
......................................................................
[IMPROV] Remove spaces between """ and it's text
Change-Id: Ifaf10d3433dddbf68be39deff6478f5f1f4b691d
---
M generate_user_files.py
M pywikibot/bot.py
M pywikibot/comms/rcstream.py
M pywikibot/comms/threadedhttp.py
M pywikibot/data/wikistats.py
M pywikibot/exceptions.py
M pywikibot/family.py
M pywikibot/interwiki_graph.py
M pywikibot/page.py
M pywikibot/pagegenerators.py
M pywikibot/site.py
M pywikibot/userinterfaces/gui.py
M pywikibot/userinterfaces/terminal_interface_base.py
M pywikibot/userinterfaces/win32_unicode.py
M pywikibot/version.py
M scripts/__init__.py
M scripts/basic.py
M scripts/category.py
M scripts/checkimages.py
M scripts/commonscat.py
M scripts/delete.py
M scripts/disambredir.py
M scripts/featured.py
M scripts/flickrripper.py
M scripts/imagerecat.py
M scripts/maintenance/cache.py
M scripts/match_images.py
M scripts/newitem.py
M scripts/protect.py
M scripts/reflinks.py
M scripts/states_redirect.py
M scripts/version.py
M scripts/weblinkchecker.py
M tests/http_tests.py
M tests/i18n/__init__.py
M tests/i18n/test.py
M tests/pagegenerators_tests.py
M tests/ui_tests.py
M tests/wikibase_tests.py
39 files changed, 118 insertions(+), 118 deletions(-)
Approvals:
Mpaa: Looks good to me, approved
jenkins-bot: Verified
diff --git a/generate_user_files.py b/generate_user_files.py
index a1c83dc..c98c535 100644
--- a/generate_user_files.py
+++ b/generate_user_files.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-""" Script to create user files (user-config.py, user-fixes.py). """
+"""Script to create user files (user-config.py, user-fixes.py)."""
#
# (C) Pywikibot team, 2010-2014
#
diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index 2e670e8..e255580 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -1001,7 +1001,7 @@
stdout(msg)
def user_confirm(self, question):
- """ Obtain user response if bot option 'always' not enabled. """
+ """Obtain user response if bot option 'always' not enabled."""
if self.getOption('always'):
return True
diff --git a/pywikibot/comms/rcstream.py b/pywikibot/comms/rcstream.py
index b5d2230..688e0f6 100644
--- a/pywikibot/comms/rcstream.py
+++ b/pywikibot/comms/rcstream.py
@@ -58,7 +58,7 @@
"""
def __init__(self, wikihost, rchost, rcport=80, rcpath='/rc', total=None):
- """ Constructor for RcListenerThread. """
+ """Constructor for RcListenerThread."""
super(RcListenerThread, self).__init__()
self.rchost = rchost
self.rcport = rcport
@@ -116,13 +116,13 @@
self.client.define(GlobalListener)
def __repr__(self):
- """ Return representation. """
+ """Return representation."""
return "<rcstream for socketio://%s@%s:%s%s>" % (
self.wikihost, self.rchost, self.rcport, self.rcpath
)
def run(self):
- """ Threaded function. Runs insided the thread when started with .start(). """
+ """Threaded function. Runs insided the thread when started with .start()."""
self.running = True
while self.running:
self.client.wait(seconds=0.1)
@@ -132,12 +132,12 @@
self.queue.put(None)
def stop(self):
- """ Stop the thread. """
+ """Stop the thread."""
self.running = False
def rc_listener(wikihost, rchost, rcport=80, rcpath='/rc', total=None):
- """ RC Changes Generator. Yields changes received from RCstream.
+ """RC Changes Generator. Yields changes received from RCstream.
@param wikihost: the hostname of the wiki we want to get changes for. This
is passed to rcstream using a 'subscribe' command. Pass
@@ -191,7 +191,7 @@
def site_rc_listener(site, total=None):
- """ RC Changes Generator. Yields changes received from RCstream.
+ """RC Changes Generator. Yields changes received from RCstream.
@param site: the Pywikibot.Site object to yield live recent changes for
@type site: Pywikibot.BaseSite
diff --git a/pywikibot/comms/threadedhttp.py b/pywikibot/comms/threadedhttp.py
index b7a7422..eb892ae 100644
--- a/pywikibot/comms/threadedhttp.py
+++ b/pywikibot/comms/threadedhttp.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-""" Httplib2 threaded cookie layer.
+"""Httplib2 threaded cookie layer.
This class extends httplib2, adding support for:
- Cookies, guarded for cross-site redirects
diff --git a/pywikibot/data/wikistats.py b/pywikibot/data/wikistats.py
index 125eabc..b8f64fe 100644
--- a/pywikibot/data/wikistats.py
+++ b/pywikibot/data/wikistats.py
@@ -235,6 +235,6 @@
reverse=True)
def languages_by_size(self, table):
- """ Return ordered list of languages by size from WikiStats. """
+ """Return ordered list of languages by size from WikiStats."""
# This assumes they appear in order of size in the WikiStats dump.
return [d['prefix'] for d in self.get(table)]
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index 4b4161d..3bb6a7a 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -174,7 +174,7 @@
message = "Edit to page %(title)s failed:\n%(reason)s"
def __init__(self, page, reason):
- """ Constructor.
+ """Constructor.
@param reason: Details of the problem
@type reason: Exception or basestring
@@ -276,7 +276,7 @@
u"Target page: %(target_page)s on %(target_site)s.")
def __init__(self, page, target_page):
- """ Constructor.
+ """Constructor.
@param target_page: Target page of the redirect.
@type reason: Page
diff --git a/pywikibot/family.py b/pywikibot/family.py
index cd90d87..0969041 100644
--- a/pywikibot/family.py
+++ b/pywikibot/family.py
@@ -1114,7 +1114,7 @@
# Which version of MediaWiki is used?
@deprecated('APISite.version()')
def version(self, code):
- """ Return MediaWiki version number as a string.
+ """Return MediaWiki version number as a string.
Use L{pywikibot.tools.MediaWikiVersion} to compare version strings.
"""
@@ -1143,7 +1143,7 @@
@deprecated("APISite.version()")
def versionnumber(self, code):
- """ DEPRECATED, use version() instead.
+ """DEPRECATED, use version() instead.
Use L{pywikibot.tools.MediaWikiVersion} to compare version strings.
Return an int identifying MediaWiki version.
diff --git a/pywikibot/interwiki_graph.py b/pywikibot/interwiki_graph.py
index 00fe657..b89f3dc 100644
--- a/pywikibot/interwiki_graph.py
+++ b/pywikibot/interwiki_graph.py
@@ -1,4 +1,4 @@
-""" Module with the Graphviz drawing calls. """
+"""Module with the Graphviz drawing calls."""
#
# (C) Pywikibot team, 2006-2010
#
diff --git a/pywikibot/page.py b/pywikibot/page.py
index c63af01..16ae491 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -2508,7 +2508,7 @@
@property
def username(self):
- """ The username.
+ """The username.
Convenience method that returns the title of the page with
namespace prefix omitted, which is the username.
@@ -2521,7 +2521,7 @@
return self.title(withNamespace=False)
def isRegistered(self, force=False):
- """ Determine if the user is registered on the site.
+ """Determine if the user is registered on the site.
It is possible to have a page named User:xyz and not have
a corresponding user with username xyz.
@@ -2540,14 +2540,14 @@
return self.getprops(force).get('missing') is None
def isAnonymous(self):
- """ Determine if the user is editing as an IP address.
+ """Determine if the user is editing as an IP address.
@return: bool
"""
return ip_regexp.match(self.username) is not None
def getprops(self, force=False):
- """ Return a properties about the user.
+ """Return a properties about the user.
@param force: if True, forces reloading the data from API
@type force: bool
@@ -2567,7 +2567,7 @@
@deprecated('User.registration()')
def registrationTime(self, force=False):
- """ DEPRECATED. Fetch registration date for this user.
+ """DEPRECATED. Fetch registration date for this user.
@param force: if True, forces reloading the data from API
@type force: bool
@@ -2580,7 +2580,7 @@
return 0
def registration(self, force=False):
- """ Fetch registration date for this user.
+ """Fetch registration date for this user.
@param force: if True, forces reloading the data from API
@type force: bool
@@ -2592,7 +2592,7 @@
return pywikibot.Timestamp.fromISOformat(reg)
def editCount(self, force=False):
- """ Return edit count for a registered user.
+ """Return edit count for a registered user.
Always returns 0 for 'anonymous' users.
@@ -2607,7 +2607,7 @@
return 0
def isBlocked(self, force=False):
- """ Determine whether the user is currently blocked.
+ """Determine whether the user is currently blocked.
@param force: if True, forces reloading the data from API
@type force: bool
@@ -2617,7 +2617,7 @@
return 'blockedby' in self.getprops(force)
def isEmailable(self, force=False):
- """ Determine whether emails may be send to this user through MediaWiki.
+ """Determine whether emails may be send to this user through MediaWiki.
@param force: if True, forces reloading the data from API
@type force: bool
@@ -2627,7 +2627,7 @@
return 'emailable' in self.getprops(force)
def groups(self, force=False):
- """ Return a list of groups to which this user belongs.
+ """Return a list of groups to which this user belongs.
The list of groups may be empty.
@@ -2642,7 +2642,7 @@
return []
def getUserPage(self, subpage=u''):
- """ Return a Page object relative to this user's main page.
+ """Return a Page object relative to this user's main page.
@param subpage: subpage part to be appended to the main
page title (optional)
@@ -2658,7 +2658,7 @@
return Page(Link(self.title() + subpage, self.site))
def getUserTalkPage(self, subpage=u''):
- """ Return a Page object relative to this user's main talk page.
+ """Return a Page object relative to this user's main talk page.
@param subpage: subpage part to be appended to the main
talk page title (optional)
@@ -2675,7 +2675,7 @@
self.site, defaultNamespace=3))
def sendMail(self, subject, text, ccme=False):
- """ Send an email to this user via MediaWiki's email interface.
+ """Send an email to this user via MediaWiki's email interface.
Return True on success, False otherwise.
This method can raise an UserActionRefuse exception in case this user
@@ -2750,7 +2750,7 @@
@deprecated("contributions")
@deprecate_arg("limit", "total") # To be consistent with rest of framework
def editedPages(self, total=500):
- """ DEPRECATED. Use contributions().
+ """DEPRECATED. Use contributions().
Yields pywikibot.Page objects that this user has
edited, with an upper bound of 'total'. Pages returned are not
@@ -2765,7 +2765,7 @@
@deprecate_arg("limit", "total") # To be consistent with rest of framework
@deprecate_arg("namespace", "namespaces")
def contributions(self, total=500, namespaces=[]):
- """ Yield tuples describing this user edits.
+ """Yield tuples describing this user edits.
Each tuple is composed of a pywikibot.Page object,
the revision id (int), the edit timestamp (as a pywikibot.Timestamp
@@ -2788,7 +2788,7 @@
@deprecate_arg("number", "total")
def uploadedImages(self, total=10):
- """ Yield tuples describing files uploaded by this user.
+ """Yield tuples describing files uploaded by this user.
Each tuple is composed of a pywikibot.Page, the timestamp (str in
ISO8601 format), comment (unicode) and a bool for pageid > 0.
@@ -2817,7 +2817,7 @@
"""
def __init__(self, site, title=u"", **kwargs):
- """ Constructor.
+ """Constructor.
If title is provided, either ns or entity_type must also be provided,
and will be checked against the title parsed using the Page
@@ -3250,7 +3250,7 @@
class ItemPage(WikibasePage):
- """ Wikibase entity of type 'item'.
+ """Wikibase entity of type 'item'.
A Wikibase item may be defined by either a 'Q' id (qid),
or by a site & title.
diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index 1a1b15a..1a73e8f 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -1339,7 +1339,7 @@
@deprecated_args(inverse="quantifier")
def titlefilter(cls, generator, regex, quantifier='any',
ignore_namespace=True):
- """ Yield pages from another generator whose title matches regex.
+ """Yield pages from another generator whose title matches regex.
Uses regex option re.IGNORECASE depending on the quantifier parameter.
@@ -2074,7 +2074,7 @@
self.site = site
def queryYahoo(self, query):
- """ Perform a query using python package 'pYsearch'. """
+ """Perform a query using python package 'pYsearch'."""
try:
from yahoo.search.web import WebSearch
except ImportError:
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 2a347bb..c0b3410 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -83,7 +83,7 @@
class LoginStatus(object):
- """ Enum for Login statuses.
+ """Enum for Login statuses.
>>> LoginStatus.NOT_ATTEMPTED
-3
@@ -126,7 +126,7 @@
class Namespace(Iterable, ComparableMixin, UnicodeMixin):
- """ Namespace site data object.
+ """Namespace site data object.
This is backwards compatible with the structure of entries
in site._namespaces which were a list of::
@@ -607,7 +607,7 @@
return (self.family.name, self.code)
def __getstate__(self):
- """ Remove Lock based classes before pickling. """
+ """Remove Lock based classes before pickling."""
new = self.__dict__.copy()
del new['_pagemutex']
if '_throttle' in new:
@@ -615,7 +615,7 @@
return new
def __setstate__(self, attrs):
- """ Restore things removed in __getstate__. """
+ """Restore things removed in __getstate__."""
self.__dict__.update(attrs)
self._pagemutex = threading.Lock()
@@ -1019,7 +1019,7 @@
def must_be(group=None, right=None):
- """ Decorator to require a certain user status when method is called.
+ """Decorator to require a certain user status when method is called.
@param group: The group the logged in user should belong to
this parameter can be overridden by
@@ -1055,7 +1055,7 @@
def need_version(version):
- """ Decorator to require a certain MediaWiki version number.
+ """Decorator to require a certain MediaWiki version number.
@param version: the mw version number required
@type version: str
@@ -1678,7 +1678,7 @@
class_name='APISite')
def logout(self):
- """ Logout of the site and load details for the logged out user.
+ """Logout of the site and load details for the logged out user.
Also logs out of the global account if linked to the user.
"""
@@ -2020,7 +2020,7 @@
@need_version("1.12")
def expand_text(self, text, title=None, includecomments=None):
- """ Parse the given text for preprocessing and rendering.
+ """Parse the given text for preprocessing and rendering.
e.g expand templates and strip comments if includecomments
parameter is not True. Keeps text inside
@@ -2165,7 +2165,7 @@
@need_version("1.14")
@deprecated("has_extension")
def hasExtension(self, name, unknown=None):
- """ Determine whether extension `name` is loaded.
+ """Determine whether extension `name` is loaded.
Use L{has_extension} instead!
@@ -2182,7 +2182,7 @@
@need_version("1.14")
def has_extension(self, name):
- """ Determine whether extension `name` is loaded.
+ """Determine whether extension `name` is loaded.
@param name: The extension to check for, case insensitive
@type name: str
@@ -3388,7 +3388,7 @@
return self.allcategories(total=limit)
def isBot(self, username):
- """Return True is username is a bot user. """
+ """Return True is username is a bot user."""
return username in [userdata['name'] for userdata in self.botusers()]
def botusers(self, step=None, total=None):
diff --git a/pywikibot/userinterfaces/gui.py b/pywikibot/userinterfaces/gui.py
index 788c541..07a4ba5 100644
--- a/pywikibot/userinterfaces/gui.py
+++ b/pywikibot/userinterfaces/gui.py
@@ -445,7 +445,7 @@
class Tkdialog:
- """ The dialog window for image info."""
+ """The dialog window for image info."""
def __init__(self, photo_description, photo, filename):
"""Constructor."""
@@ -526,18 +526,18 @@
return imageTk
def ok_file(self):
- """ The user pressed the OK button. """
+ """The user pressed the OK button."""
self.filename = self.filename_field.get()
self.photo_description = self.description_field.get(0.0, Tkinter.END)
self.root.destroy()
def skip_file(self):
- """ The user pressed the Skip button. """
+ """The user pressed the Skip button."""
self.skip = True
self.root.destroy()
def show_dialog(self):
- """ Activate the dialog.
+ """Activate the dialog.
@return: new description, name, and if the image is skipped
@rtype: tuple of (unicode, unicode, bool)
diff --git a/pywikibot/userinterfaces/terminal_interface_base.py b/pywikibot/userinterfaces/terminal_interface_base.py
index a900870..6e105de 100755
--- a/pywikibot/userinterfaces/terminal_interface_base.py
+++ b/pywikibot/userinterfaces/terminal_interface_base.py
@@ -403,7 +403,7 @@
self.UI = UI
def flush(self):
- """Flush the stream. """
+ """Flush the stream."""
self.stream.flush()
def emit(self, record):
diff --git a/pywikibot/userinterfaces/win32_unicode.py b/pywikibot/userinterfaces/win32_unicode.py
index dc85cc2..9e4dded 100755
--- a/pywikibot/userinterfaces/win32_unicode.py
+++ b/pywikibot/userinterfaces/win32_unicode.py
@@ -1,4 +1,4 @@
-""" Stdout, stderr and argv support for unicode. """
+"""Stdout, stderr and argv support for unicode."""
##############################################
# Support for unicode in windows cmd.exe
# Posted on Stack Overflow [1], available under CC-BY-SA [2]
diff --git a/pywikibot/version.py b/pywikibot/version.py
index ce95775..377339c 100644
--- a/pywikibot/version.py
+++ b/pywikibot/version.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-""" Module to determine the pywikibot version (tag, revision and date). """
+"""Module to determine the pywikibot version (tag, revision and date)."""
#
# (C) Merlijn 'valhallasw' van Deen, 2007-2014
# (C) xqt, 2010-2014
@@ -285,7 +285,7 @@
def package_versions(modules=None, builtins=False, standard_lib=None):
- """ Retrieve package version information.
+ """Retrieve package version information.
When builtins or standard_lib are None, they will be included only
if a version was found in the package.
diff --git a/scripts/__init__.py b/scripts/__init__.py
index 6eb2664..ab8c50a 100644
--- a/scripts/__init__.py
+++ b/scripts/__init__.py
@@ -1 +1 @@
-""" THIS DIRECTORY IS TO HOLD BOT SCRIPTS FOR THE NEW FRAMEWORK. """
+"""THIS DIRECTORY IS TO HOLD BOT SCRIPTS FOR THE NEW FRAMEWORK."""
diff --git a/scripts/basic.py b/scripts/basic.py
index 9c315ea..33d6319 100755
--- a/scripts/basic.py
+++ b/scripts/basic.py
@@ -62,12 +62,12 @@
self.summary = i18n.twtranslate(site, 'basic-changing')
def run(self):
- """ Process each page from the generator. """
+ """Process each page from the generator."""
for page in self.generator:
self.treat(page)
def treat(self, page):
- """ Load the given page, does some changes, and saves it. """
+ """Load the given page, does some changes, and saves it."""
text = self.load(page)
if not text:
return
@@ -84,7 +84,7 @@
pywikibot.output(u'Page %s not saved.' % page.title(asLink=True))
def load(self, page):
- """ Load the text of the given page. """
+ """Load the text of the given page."""
try:
# Load the page
text = page.get()
@@ -100,7 +100,7 @@
def save(self, text, page, comment=None, minorEdit=True,
botflag=True):
- """ Update the given page with new text. """
+ """Update the given page with new text."""
# only save if something was changed
if text != page.get():
# Show the title of the page we're working on.
diff --git a/scripts/category.py b/scripts/category.py
index bec702b..2236f11 100755
--- a/scripts/category.py
+++ b/scripts/category.py
@@ -953,7 +953,7 @@
class CategoryTreeRobot:
- """ Robot to create tree overviews of the category structure.
+ """Robot to create tree overviews of the category structure.
Parameters:
* catTitle - The category which will be the tree's root.
@@ -976,7 +976,7 @@
self.site = pywikibot.Site()
def treeview(self, cat, currentDepth=0, parent=None):
- """ Return a tree view of all subcategories of cat.
+ """Return a tree view of all subcategories of cat.
The multi-line string contains a tree view of all subcategories of cat,
up to level maxDepth. Recursively calls itself.
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index e792828..7b94bdb 100644
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -638,7 +638,7 @@
def report(self, newtext, image_to_report, notification=None, head=None,
notification2=None, unver=True, commTalk=None, commImage=None):
- """ Function to make the reports easier. """
+ """Function to make the reports easier."""
self.image_to_report = image_to_report
self.newtext = newtext
self.head = head or u''
@@ -744,7 +744,7 @@
return True
def put_mex_in_talk(self):
- """ Function to put the warning in talk page of the uploader."""
+ """Function to put the warning in talk page of the uploader."""
commento2 = i18n.translate(self.site, msg_comm2, fallback=True)
emailPageName = i18n.translate(self.site, emailPageWithText)
emailSubj = i18n.translate(self.site, emailSubject)
@@ -937,7 +937,7 @@
return True
def checkImageDuplicated(self, duplicates_rollback):
- """ Function to check the duplicated files. """
+ """Function to check the duplicated files."""
dupText = i18n.translate(self.site, duplicatesText)
dupRegex = i18n.translate(self.site, duplicatesRegex)
dupTalkHead = i18n.translate(self.site, duplicate_user_talk_head)
@@ -1093,7 +1093,7 @@
def report_image(self, image_to_report, rep_page=None, com=None,
rep_text=None, addings=True, regex=None):
- """ Report the files to the report page when needed. """
+ """Report the files to the report page when needed."""
if not rep_page:
rep_page = self.rep_page
@@ -1149,7 +1149,7 @@
return reported
def takesettings(self):
- """ Function to take the settings from the wiki. """
+ """Function to take the settings from the wiki."""
settingsPage = i18n.translate(self.site, page_with_settings)
try:
if not settingsPage:
@@ -1404,7 +1404,7 @@
return (self.license_found, self.whiteTemplatesFound)
def load(self, raw):
- """ Load a list of objects from a string using regex. """
+ """Load a list of objects from a string using regex."""
list_loaded = []
# I search with a regex how many user have not the talk page
# and i put them in a list (i find it more easy and secure)
@@ -1417,7 +1417,7 @@
return list_loaded
def skipImages(self, skip_number, limit):
- """ Given a number of files, skip the first -number- files. """
+ """Given a number of files, skip the first -number- files."""
# If the images to skip are more the images to check, make them the
# same number
if skip_number == 0:
@@ -1516,7 +1516,7 @@
return generator
def isTagged(self):
- """ Understand if a file is already tagged or not. """
+ """Understand if a file is already tagged or not."""
# Is the image already tagged? If yes, no need to double-check, skip
for i in i18n.translate(self.site, txt_find):
# If there are {{ use regex, otherwise no (if there's not the
diff --git a/scripts/commonscat.py b/scripts/commonscat.py
index 74c9d39..b078987 100755
--- a/scripts/commonscat.py
+++ b/scripts/commonscat.py
@@ -234,7 +234,7 @@
self.site = pywikibot.Site()
def treat(self, page):
- """ Load the given page, do some changes, and save it. """
+ """Load the given page, do some changes, and save it."""
if not page.exists():
pywikibot.output(u'Page %s does not exist. Skipping.'
% page.title(asLink=True))
@@ -342,7 +342,7 @@
def changeCommonscat(self, page=None, oldtemplate=u'', oldcat=u'',
newtemplate=u'', newcat=u'', linktitle=u'',
description=NotImplemented): # pylint: disable=unused-argument
- """ Change the current commonscat template and target. """
+ """Change the current commonscat template and target."""
if oldcat == '3=S' or linktitle == '3=S':
return # TODO: handle additional param on de-wiki
if not linktitle and (page.title().lower() in oldcat.lower() or
@@ -437,7 +437,7 @@
return None
def checkCommonscatLink(self, name=""):
- """ Return the name of a valid commons category.
+ """Return the name of a valid commons category.
If the page is a redirect this function tries to follow it.
If the page doesn't exists the function will return an empty string
diff --git a/scripts/delete.py b/scripts/delete.py
index 5bc1904..e6fb2f1 100644
--- a/scripts/delete.py
+++ b/scripts/delete.py
@@ -49,7 +49,7 @@
class DeletionRobot(CurrentPageBot):
- """ This robot allows deletion of pages en masse. """
+ """This robot allows deletion of pages en masse."""
def __init__(self, generator, summary, **kwargs):
"""
diff --git a/scripts/disambredir.py b/scripts/disambredir.py
index 8739f3a..af697bb 100644
--- a/scripts/disambredir.py
+++ b/scripts/disambredir.py
@@ -42,7 +42,7 @@
def treat(text, linkedPage, targetPage):
- """ Based on the method of the same name in solve_disambiguation.py. """
+ """Based on the method of the same name in solve_disambiguation.py."""
# make a backup of the original text so we can show the changes later
mysite = pywikibot.Site()
linktrail = mysite.linktrail()
diff --git a/scripts/featured.py b/scripts/featured.py
index 184612f..b5957a6 100644
--- a/scripts/featured.py
+++ b/scripts/featured.py
@@ -498,7 +498,7 @@
return add_templates, remove_templates
def featuredWithInterwiki(self, fromsite, task):
- """ Read featured articles and find the corresponding pages.
+ """Read featured articles and find the corresponding pages.
Find corresponding pages on other sites, place the template and
remember the page in the cache dict.
diff --git a/scripts/flickrripper.py b/scripts/flickrripper.py
index 7a4fc9e..e7cd008 100644
--- a/scripts/flickrripper.py
+++ b/scripts/flickrripper.py
@@ -131,7 +131,7 @@
def findDuplicateImages(photo=None,
site=pywikibot.Site(u'commons', u'commons')):
- """ Find duplicate images.
+ """Find duplicate images.
Take the photo, calculate the SHA1 hash and ask the MediaWiki api
for a list of duplicates.
@@ -168,7 +168,7 @@
def getFilename(photoInfo=None, site=None, project=u'Flickr'):
- """ Build a good filename for the upload based on the username and title.
+ """Build a good filename for the upload based on the username and title.
Prevents naming collisions.
@@ -210,7 +210,7 @@
def cleanUpTitle(title):
- """ Clean up the title of a potential MediaWiki page.
+ """Clean up the title of a potential MediaWiki page.
Otherwise the title of the page might not be allowed by the software.
@@ -238,7 +238,7 @@
def buildDescription(flinfoDescription=u'', flickrreview=False, reviewer=u'',
override=u'', addCategory=u'', removeCategories=False):
- """ Build the final description for the image.
+ """Build the final description for the image.
The description is based on the info from flickrinfo and improved.
@@ -333,7 +333,7 @@
def getPhotos(flickr=None, user_id=u'', group_id=u'', photoset_id=u'',
start_id='', end_id='', tags=u''):
- """ Loop over a set of Flickr photos. """
+ """Loop over a set of Flickr photos."""
found_start_id = not start_id
# https://www.flickr.com/services/api/flickr.groups.pools.getPhotos.html
diff --git a/scripts/imagerecat.py b/scripts/imagerecat.py
index 7bf8f1d..ab8d03f 100644
--- a/scripts/imagerecat.py
+++ b/scripts/imagerecat.py
@@ -74,7 +74,7 @@
def categorizeImages(generator, onlyFilter, onlyUncat):
- """ Loop over all images in generator and try to categorize them.
+ """Loop over all images in generator and try to categorize them.
Get category suggestions from CommonSense.
@@ -113,7 +113,7 @@
def getCommonshelperCats(imagepage):
- """ Get category suggestions from CommonSense.
+ """Get category suggestions from CommonSense.
@rtype: list of unicode
@@ -290,7 +290,7 @@
def applyAllFilters(categories):
- """ Apply all filters on categories. """
+ """Apply all filters on categories."""
result = []
result = filterDisambiguation(categories)
result = followRedirects(result)
@@ -301,7 +301,7 @@
def filterBlacklist(categories):
- """ Filter out categories which are on the blacklist. """
+ """Filter out categories which are on the blacklist."""
result = []
for cat in categories:
cat = cat.replace('_', ' ')
@@ -311,7 +311,7 @@
def filterDisambiguation(categories):
- """ Filter out disambiguation categories. """
+ """Filter out disambiguation categories."""
result = []
for cat in categories:
if (not pywikibot.Page(pywikibot.Site(u'commons', u'commons'),
@@ -321,7 +321,7 @@
def followRedirects(categories):
- """ If a category is a redirect, replace the category with the target. """
+ """If a category is a redirect, replace the category with the target."""
result = []
for cat in categories:
categoryPage = pywikibot.Page(pywikibot.Site(u'commons', u'commons'),
@@ -336,7 +336,7 @@
def filterCountries(categories):
- """ Try to filter out ...by country categories.
+ """Try to filter out ...by country categories.
First make a list of any ...by country categories and try to find some
countries. If a by country category has a subcategoy containing one of the
@@ -369,7 +369,7 @@
def filterParents(categories):
- """ Remove all parent categories from the set to prevent overcategorization. """
+ """Remove all parent categories from the set to prevent overcategorization."""
result = []
toFilter = u''
for cat in categories:
@@ -394,7 +394,7 @@
def saveImagePage(imagepage, newcats, usage, galleries, onlyFilter):
- """ Remove the old categories and add the new categories to the image. """
+ """Remove the old categories and add the new categories to the image."""
newtext = textlib.removeCategoryLinks(imagepage.text, imagepage.site)
if not onlyFilter:
newtext = removeTemplates(newtext)
diff --git a/scripts/maintenance/cache.py b/scripts/maintenance/cache.py
index e9c96ff..2b84d3c 100644
--- a/scripts/maintenance/cache.py
+++ b/scripts/maintenance/cache.py
@@ -59,7 +59,7 @@
class ParseError(Exception):
- """ Error parsing. """
+ """Error parsing."""
class CacheEntry(api.CachedRequest):
@@ -67,7 +67,7 @@
"""A Request cache entry."""
def __init__(self, directory, filename):
- """ Constructor. """
+ """Constructor."""
self.directory = directory
self.filename = filename
@@ -78,11 +78,11 @@
return self._cachefile_path()
def _create_file_name(self):
- """ Filename of the cached entry. """
+ """Filename of the cached entry."""
return self.filename
def _get_cache_dir(self):
- """ Directory of the cached entry. """
+ """Directory of the cached entry."""
return self.directory
def _cachefile_path(self):
@@ -90,13 +90,13 @@
self._create_file_name())
def _load_cache(self):
- """ Load the cache entry. """
+ """Load the cache entry."""
with open(self._cachefile_path(), 'rb') as f:
self.key, self._data, self._cachetime = pickle.load(f)
return True
def parse_key(self):
- """ Parse the key loaded from the cache entry. """
+ """Parse the key loaded from the cache entry."""
# find the start of the first parameter
start = self.key.index('(')
# find the end of the first object
@@ -153,7 +153,7 @@
return self._parsed_key
def _rebuild(self):
- """ Reconstruct the original Request from the key. """
+ """Reconstruct the original Request from the key."""
if hasattr(self, '_parsed_key'):
(site, username, login_status, params) = self._parsed_key
else:
@@ -171,7 +171,7 @@
self._params = dict(eval(params))
def _delete(self):
- """ Delete the cache entry. """
+ """Delete the cache entry."""
os.remove(self._cachefile_path())
@@ -248,25 +248,25 @@
def has_password(entry):
- """ Entry has a password in the entry. """
+ """Entry has a password in the entry."""
if 'lgpassword' in entry._uniquedescriptionstr():
return entry
def is_logout(entry):
- """ Entry is a logout entry. """
+ """Entry is a logout entry."""
if not entry._data and 'logout' in entry.key:
return entry
def empty_response(entry):
- """ Entry has no data. """
+ """Entry has no data."""
if not entry._data and 'logout' not in entry.key:
return entry
def not_accessed(entry):
- """ Entry has never been accessed. """
+ """Entry has never been accessed."""
if not hasattr(entry, 'stinfo'):
return
diff --git a/scripts/match_images.py b/scripts/match_images.py
index 55076e1..915d1be 100644
--- a/scripts/match_images.py
+++ b/scripts/match_images.py
@@ -108,7 +108,7 @@
def get_image_from_image_page(imagePage):
- """ Get the image object to work based on an imagePage object. """
+ """Get the image object to work based on an imagePage object."""
imageBuffer = None
imageURL = imagePage.fileUrl()
imageURLopener = http.fetch(imageURL)
@@ -118,7 +118,7 @@
def match_images(imageA, imageB):
- """ Match two image objects. Return the ratio of pixels that match. """
+ """Match two image objects. Return the ratio of pixels that match."""
histogramA = imageA.histogram()
histogramB = imageB.histogram()
@@ -139,7 +139,7 @@
def main(*args):
- """ Extracting file page information of images to work on and initiate matching. """
+ """Extracting file page information of images to work on and initiate matching."""
images = []
other_family = u''
other_lang = u''
diff --git a/scripts/newitem.py b/scripts/newitem.py
index acba3da..89577bb 100644
--- a/scripts/newitem.py
+++ b/scripts/newitem.py
@@ -34,7 +34,7 @@
class NewItemRobot(WikidataBot):
- """ A bot to create new items. """
+ """A bot to create new items."""
def __init__(self, generator, **kwargs):
"""Only accepts options defined in availableOptions."""
@@ -59,7 +59,7 @@
% (self.lastEdit, self.lastEditBefore.isoformat()))
def treat(self, page, item):
- """ Treat page/item. """
+ """Treat page/item."""
if item and item.exists():
pywikibot.output(u'%s already has an item: %s.' % (page, item))
if self.getOption('touch'):
diff --git a/scripts/protect.py b/scripts/protect.py
index 2bfaade..c5d259a 100644
--- a/scripts/protect.py
+++ b/scripts/protect.py
@@ -63,7 +63,7 @@
class ProtectionRobot(Bot):
- """ This bot allows protection of pages en masse. """
+ """This bot allows protection of pages en masse."""
def __init__(self, generator, protections, **kwargs):
"""
diff --git a/scripts/reflinks.py b/scripts/reflinks.py
index 415d94d..f50083b 100644
--- a/scripts/reflinks.py
+++ b/scripts/reflinks.py
@@ -472,7 +472,7 @@
% (err_num, link, pagetitleaslink), toStdout=True)
def getPDFTitle(self, ref, f):
- """ Use pdfinfo to retrieve title from a PDF.
+ """Use pdfinfo to retrieve title from a PDF.
FIXME: Unix-only, I'm afraid.
diff --git a/scripts/states_redirect.py b/scripts/states_redirect.py
index 19c5e1c..f184df5 100644
--- a/scripts/states_redirect.py
+++ b/scripts/states_redirect.py
@@ -71,7 +71,7 @@
self.abbrev[subd.name] = subd.code[3:]
def treat(self, page):
- """ Re-directing process.
+ """Re-directing process.
Check if pages are in the given form Something, State, and
if so, create a redirect from Something, ST..
diff --git a/scripts/version.py b/scripts/version.py
index e50a0b6..fb43be1 100755
--- a/scripts/version.py
+++ b/scripts/version.py
@@ -1,6 +1,6 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
-""" Script to determine the Pywikibot version (tag, revision and date). """
+"""Script to determine the Pywikibot version (tag, revision and date)."""
#
# (C) Merlijn 'valhallasw' van Deen, 2007-2008
# (C) xqt, 2010-2014
diff --git a/scripts/weblinkchecker.py b/scripts/weblinkchecker.py
index ba33030..4c36069 100644
--- a/scripts/weblinkchecker.py
+++ b/scripts/weblinkchecker.py
@@ -501,7 +501,7 @@
class LinkCheckThread(threading.Thread):
- """ A thread responsible for checking one URL.
+ """A thread responsible for checking one URL.
After checking the page, it will die.
"""
@@ -654,7 +654,7 @@
return False
def save(self):
- """ Save the .dat file to disk. """
+ """Save the .dat file to disk."""
with open(self.datfilename, 'wb') as f:
pickle.dump(self.historyDict, f, protocol=config.pickle_protocol)
diff --git a/tests/http_tests.py b/tests/http_tests.py
index 63b5113..3c49acd 100644
--- a/tests/http_tests.py
+++ b/tests/http_tests.py
@@ -334,7 +334,7 @@
config.user_agent_format = self.orig_format
def test_default_user_agent(self):
- """ Config defined format string test. """
+ """Config defined format string test."""
self.assertTrue(http.user_agent().startswith(
pywikibot.calledModuleName()))
self.assertIn('Pywikibot/' + pywikibot.__release__, http.user_agent())
diff --git a/tests/i18n/__init__.py b/tests/i18n/__init__.py
index 66f0234..f1a0213 100644
--- a/tests/i18n/__init__.py
+++ b/tests/i18n/__init__.py
@@ -1 +1 @@
-""" Test i18n data package. """
+"""Test i18n data package."""
diff --git a/tests/i18n/test.py b/tests/i18n/test.py
index de5d92c..44afee0 100644
--- a/tests/i18n/test.py
+++ b/tests/i18n/test.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-""" Test i18n data. """
+"""Test i18n data."""
msg = {
'de': {
'test-plural': u'Bot: Ändere %(num)d {{PLURAL:num|Seite|Seiten}}.',
diff --git a/tests/pagegenerators_tests.py b/tests/pagegenerators_tests.py
index 8a6166f..35e6320 100755
--- a/tests/pagegenerators_tests.py
+++ b/tests/pagegenerators_tests.py
@@ -792,7 +792,7 @@
class LiveRCPageGeneratorTestCase(WikimediaDefaultSiteTestCase):
- """ Test case for Live Recent Changes pagegenerator.
+ """Test case for Live Recent Changes pagegenerator.
Works best on a busy site, as three changes are requested
"""
diff --git a/tests/ui_tests.py b/tests/ui_tests.py
index 08ddcb8..087a230 100644
--- a/tests/ui_tests.py
+++ b/tests/ui_tests.py
@@ -408,7 +408,7 @@
'\x1b[0m normal text\n\x1b[0m')
def testOutputColorCascade_incorrect(self):
- """ Test incorrect behavior of testOutputColorCascade. """
+ """Test incorrect behavior of testOutputColorCascade."""
pywikibot.output(self.str2)
self.assertEqual(newstdout.getvalue(), '')
self.assertEqual(
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index b0b7cfa..41e90c2 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -69,7 +69,7 @@
self.assertEqual(claim._formatValue(), {'entity-type': 'item', 'numeric-id': 1})
def test_cmp(self):
- """ Test WikibasePage.__cmp__. """
+ """Test WikibasePage.__cmp__."""
self.assertEqual(pywikibot.ItemPage.fromPage(self.mainpage),
pywikibot.ItemPage(self.get_repo(), 'q5296'))
--
To view, visit https://gerrit.wikimedia.org/r/189740
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ifaf10d3433dddbf68be39deff6478f5f1f4b691d
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: Siebrand <siebrand(a)kitano.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Only use apt-get for PYSETUP_TEST_EXTRAS
......................................................................
Only use apt-get for PYSETUP_TEST_EXTRAS
Saves ~10s per build
Change-Id: Ie9585a26a9e94f6d1014a6cdbcb74faf4a56758e
---
M .travis.yml
1 file changed, 2 insertions(+), 2 deletions(-)
Approvals:
John Vandenberg: Looks good to me, but someone else must approve
XZise: Looks good to me, approved
jenkins-bot: Verified
diff --git a/.travis.yml b/.travis.yml
index fc2a251..addcc33 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -8,8 +8,8 @@
- '2.6'
before_install:
- - sudo apt-get update -qq
- - sudo apt-get install -y liblua5.1-dev
+ - if [[ "$PYSETUP_TEST_EXTRAS" == "1" ]]; then sudo apt-get update -qq; fi
+ - if [[ "$PYSETUP_TEST_EXTRAS" == "1" ]]; then sudo apt-get install -y liblua5.1-dev; fi
install:
- if [[ "$SITE_ONLY" == '1' ]]; then export USE_NOSE=1; fi
--
To view, visit https://gerrit.wikimedia.org/r/189635
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ie9585a26a9e94f6d1014a6cdbcb74faf4a56758e
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Improvement for counting user edits
......................................................................
Improvement for counting user edits
- use revisions generator instead of deprecated getVersionHistory
Change-Id: Ib765e0ca0ae15743d52e9cb6c9eee80492848223
---
M scripts/checkimages.py
1 file changed, 2 insertions(+), 12 deletions(-)
Approvals:
Mpaa: Looks good to me, approved
jenkins-bot: Verified
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index 19f07e6..6745389 100644
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -82,7 +82,7 @@
# (C) Kyle/Orgullomoore, 2006-2007 (newimage.py)
# (C) Siebrand Mazeland, 2007-2010
# (C) Filnik, 2007-2011
-# (C) Pywikibot team, 2007-2014
+# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
@@ -875,20 +875,10 @@
def countEdits(self, pagename, userlist):
"""Function to count the edit of a user or a list of users in a page."""
- # self.botolist
if isinstance(userlist, basestring):
userlist = [userlist]
page = pywikibot.Page(self.site, pagename)
- history = page.getVersionHistory()
- user_list = list()
-
- for data in history:
- user_list.append(data.user)
- number_edits = 0
-
- for username in userlist:
- number_edits += user_list.count(username)
- return number_edits
+ return sum(1 for rev in page.revisions() if rev.user in userlist)
def checkImageOnCommons(self):
"""Checking if the file is on commons."""
--
To view, visit https://gerrit.wikimedia.org/r/188821
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: Ib765e0ca0ae15743d52e9cb6c9eee80492848223
Gerrit-PatchSet: 5
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
jenkins-bot has submitted this change and it was merged.
Change subject: Pages revisions code cleanup
......................................................................
Pages revisions code cleanup
- Use Page.revisions() generator to retrieve Revision objects.
This is derived from site.loadrevisions and will solve some
bugs like T66188 and T57261
- add rollback parameter for revisions method already supported
by loadrevisions
- getVersionHistory() and fullVersionHistory() are deprecated
and it is recommended to use revisions() instead.
- __getitem__() if Revision class enables indexed read access to
its values. This may be used for format strings, a sample is made
in getVersionHistoryTable()
- deprecate some args on several methods, rename "reverseOrder"
with "reverse" and "getText" with "content"
- use Page.revisions methid for latest_revision_id() and
latest_revision() methods
Change-Id: I35fe88849655b7dda3763ac7fa37802d8149e636
---
M pywikibot/page.py
1 file changed, 41 insertions(+), 39 deletions(-)
Approvals:
John Vandenberg: Looks good to me, but someone else must approve
Ladsgroup: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 6fa838d..2c5766b 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -420,7 +420,7 @@
def latest_revision_id(self):
"""Return the current revision id for this page."""
if not hasattr(self, '_revid'):
- self.site.loadrevisions(self)
+ self.revisions(self)
return self._revid
@deprecated('latest_revision_id')
@@ -431,10 +431,7 @@
@property
def latest_revision(self):
"""Return the current revision for this page."""
- rev = self.latest_revision_id
- if rev not in self._revisions:
- self.site.loadrevisions(self)
- return self._revisions[rev]
+ return next(self.revisions(content=True, total=1))
@property
def text(self):
@@ -1371,68 +1368,63 @@
"""
return self.site.getredirtarget(self)
- def revisions(self, reverseOrder=False, step=None, total=None):
+ @deprecated_args(getText='content', reverseOrder='reverse')
+ def revisions(self, reverse=False, step=None, total=None, content=False,
+ rollback=False):
"""Generator which loads the version history as Revision instances."""
# TODO: Only request uncached revisions
- self.site.loadrevisions(self, getText=False, rvdir=reverseOrder,
- step=step, total=total)
+ self.site.loadrevisions(self, getText=content, rvdir=reverse,
+ step=step, total=total, rollback=rollback)
return (self._revisions[rev] for rev in
- sorted(self._revisions, reverse=not reverseOrder)[:total])
+ sorted(self._revisions, reverse=not reverse)[:total])
# BREAKING CHANGE: in old framework, default value for getVersionHistory
# returned no more than 500 revisions; now, it iterates
# all revisions unless 'total' argument is used
- @deprecated_args(forceReload=None, revCount="total", getAll=None)
- def getVersionHistory(self, reverseOrder=False, step=None, total=None):
+ @deprecated('Page.revisions()')
+ @deprecated_args(forceReload=None, revCount='total', getAll=None,
+ reverseOrder='reverse')
+ def getVersionHistory(self, reverse=False, step=None, total=None):
"""Load the version history page and return history information.
Return value is a list of tuples, where each tuple represents one
edit and is built of revision id, edit date/time, user name, and
edit summary. Starts with the most current revision, unless
- reverseOrder is True.
+ reverse is True.
@param step: limit each API call to this number of revisions
@param total: iterate no more than this number of revisions in total
"""
- self.site.loadrevisions(self, getText=False, rvdir=reverseOrder,
- step=step, total=total)
-
return [rev.hist_entry()
- for revid, rev in sorted(self._revisions.items(),
- reverse=not reverseOrder)
- ][:total]
+ for rev in self.revisions(reverse=reverse,
+ step=step, total=total)
+ ]
- @deprecated_args(forceReload=None)
- def getVersionHistoryTable(self, reverseOrder=False, step=None, total=None):
+ @deprecated_args(forceReload=None, reverseOrder='reverse')
+ def getVersionHistoryTable(self, reverse=False, step=None, total=None):
"""Return the version history as a wiki table."""
result = '{| class="wikitable"\n'
result += '! oldid || date/time || username || edit summary\n'
- for entry in self.getVersionHistory(reverseOrder=reverseOrder,
- step=step, total=total):
+ for entry in self.revisions(reverse=reverse, step=step, total=total):
result += '|----\n'
- result += '| %s || %s || %s || <nowiki>%s</nowiki>\n' % entry
+ result += ('| {r.revid} || {r.timestamp} || {r.user} || '
+ '<nowiki>{r.comment}</nowiki>\n'.format(r=entry))
result += '|}\n'
return result
- def fullVersionHistory(self, reverseOrder=False, step=None,
- total=None, rollback=False):
+ @deprecated("Page.revisions(content=True)")
+ @deprecated_args(reverseOrder='reverse', rollback=None)
+ def fullVersionHistory(self, reverse=False, step=None, total=None):
"""Iterate previous versions including wikitext.
Takes same arguments as getVersionHistory.
- @param rollback: Returns rollback token.
- @return: A generator that yields tuples consisting of revision ID,
- edit date/time, user name and content
-
"""
- self.site.loadrevisions(self, getText=True, rvdir=reverseOrder,
- step=step, total=total, rollback=rollback)
-
- return [rev.hist_entry()
- for revid, rev in sorted(self._revisions.items(),
- reverse=not reverseOrder)
- ][:total]
+ return [rev.full_hist_entry()
+ for rev in self.revisions(content=True, reverse=reverse,
+ step=step, total=total)
+ ]
def contributingUsers(self, step=None, total=None):
"""Return a set of usernames (or IPs) of users who edited this page.
@@ -1441,9 +1433,8 @@
@param total: iterate no more than this number of revisions in total
"""
- history = self.getVersionHistory(step=step, total=total)
- users = set(entry.user for entry in history)
- return users
+ return set(entry.user for entry in self.revisions(step=step,
+ total=total))
@deprecated('oldest_revision')
def getCreator(self):
@@ -4157,6 +4148,17 @@
return Revision.FullHistEntry(self.revid, self.timestamp, self.user,
self.text, self.rollbacktoken)
+ def __getitem__(self, key):
+ """Give access to Revision class values by key.
+
+ Revision class may also give access to its values by keys
+ e.g. revid parameter may be assigned by revision['revid']
+ as well as revision.revid. This makes formatting strings with
+ % operator easier.
+
+ """
+ return getattr(self, key)
+
class Link(ComparableMixin):
--
To view, visit https://gerrit.wikimedia.org/r/135745
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I35fe88849655b7dda3763ac7fa37802d8149e636
Gerrit-PatchSet: 7
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: Ricordisamoa <ricordisamoa(a)openmailbox.org>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot <>
Build Update for wikimedia/pywikibot-core
-------------------------------------
Build: #1966
Status: Fixed
Duration: 44 minutes and 31 seconds
Commit: 4521cb0 (master)
Author: Fabian Neundorf
Message: [IMPROV] Pagegen: Exit intersect if a gen is empty
If a generator is already empty before the intersect_generator is
started it shouldn't initialize anything and always return immediately
to avoid creating any nonsensical threads.
Change-Id: I36908a79adb7d8c692af40725e343b021354aba5
View the changeset: https://github.com/wikimedia/pywikibot-core/compare/c4619f3a9472...4521cb08…
View the full build log and details: https://travis-ci.org/wikimedia/pywikibot-core/builds/49908017
--
You can configure recipients for build notifications in your .travis.yml file. See http://docs.travis-ci.com/user/notifications
jenkins-bot has submitted this change and it was merged.
Change subject: [IMPROV] Pagegen: Exit intersect if a gen is empty
......................................................................
[IMPROV] Pagegen: Exit intersect if a gen is empty
If a generator is already empty before the intersect_generator is
started it shouldn't initialize anything and always return immediately
to avoid creating any nonsensical threads.
Change-Id: I36908a79adb7d8c692af40725e343b021354aba5
---
M pywikibot/tools.py
1 file changed, 7 insertions(+), 0 deletions(-)
Approvals:
John Vandenberg: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/tools.py b/pywikibot/tools.py
index e3cf994..dd5ec2c 100644
--- a/pywikibot/tools.py
+++ b/pywikibot/tools.py
@@ -418,6 +418,13 @@
@param genlist: list of page generators
@type genlist: list
"""
+ # If any generator is empty, no pages are going to be returned
+ for source in genlist:
+ if not source:
+ debug('At least one generator ({0!r}) is empty and execution was '
+ 'skipped immediately.'.format(source), 'intersect')
+ return
+
# Item is cached to check that it is found n_gen
# times before being yielded.
cache = collections.defaultdict(set)
--
To view, visit https://gerrit.wikimedia.org/r/186596
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I36908a79adb7d8c692af40725e343b021354aba5
Gerrit-PatchSet: 4
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Ladsgroup <ladsgroup(a)gmail.com>
Gerrit-Reviewer: Merlijn van Deen <valhallasw(a)arctus.nl>
Gerrit-Reviewer: Mpaa <mpaa.wiki(a)gmail.com>
Gerrit-Reviewer: XZise <CommodoreFabianus(a)gmx.de>
Gerrit-Reviewer: jenkins-bot <>