jenkins-bot has submitted this change. (
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/589016 )
Change subject: [cleanup] instantiate a CosmeticChangesToolkit by passing a page
......................................................................
[cleanup] instantiate a CosmeticChangesToolkit by passing a page
The CosmeticChangesToolkit interface was expanded step by step
but the parameters were kept due to historical reason even though
most of them can be derived from page object directly.
- instantiate the CosmeticChangesToolkit from a page object
- only allow keyword arguments except for page parameter
- update doc of initializer
- show a FutureWarning if a CosmeticChangesToolkit is still created
by site, namespace and pageTitle
- raise a TypeError if a CosmeticChangesToolkit is created by a page
object and namespace or pageTitle are still given
- show FutureWarning to deprecate from_page method
- update CosmeticChangesToolkit calls in page library
and cosmetic_changes.py
A FutureWarning will be shown in favour of DeprecationWarning to
switch the code by passing a page very shortly. This gives us the
ability to get and set the text from and to the page object
directly if applicable.
Change-Id: Ic98fe7a01a221972c6474871679769a98240d99e
---
M pywikibot/cosmetic_changes.py
M pywikibot/page/__init__.py
M scripts/cosmetic_changes.py
3 files changed, 57 insertions(+), 24 deletions(-)
Approvals:
Hazard-SJ: Looks good to me, but someone else must approve
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index f84d6c8..dcf3af5 100755
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -58,6 +58,8 @@
#
import re
+from typing import Optional
+
import pywikibot
from pywikibot.page import url2unicode
@@ -66,7 +68,8 @@
_get_regexes, _MultiTemplateMatchBuilder, FILE_LINK_REGEX
)
from pywikibot.tools import (
- deprecated, deprecated_args, first_lower, first_upper
+ deprecated, deprecated_args, first_lower, first_upper,
+ issue_deprecation_warning,
)
try:
@@ -203,20 +206,47 @@
"""Cosmetic changes toolkit."""
- @deprecated_args(debug='show_diff', redirect=None, diff='show_diff')
- def __init__(self, site, show_diff=False, namespace=None, pageTitle=None,
- ignore=CANCEL_ALL):
- """Initializer."""
- self.site = site
+ @deprecated_args(redirect=None, diff='show_diff', site='page')
+ def __init__(self, page, *,
+ show_diff: bool = False,
+ namespace: Optional[int] = None,
+ pageTitle: Optional[str] = None,
+ ignore: int = CANCEL_ALL):
+ """Initializer.
+
+ @param page: the Page object containing the text to be modified
+ @type page: pywikibot.Page
+ @param show_diff: show difference after replacements (default: False)
+ @param namespace: DEPRECATED namespace parameter
+ @param pageTitle: DEPRECATED page title parameter
+ @param ignore: ignores if an error occurred and either skips the page
+ or only that method. It can be set one of the CANCEL constants
+ """
+ if isinstance(page, pywikibot.BaseSite):
+ self.site = page
+ self.title = pageTitle
+ try:
+ self.namespace = self.site.namespaces.resolve(namespace).pop(0)
+ except (KeyError, TypeError, IndexError):
+ raise ValueError('{} needs a valid namespace'
+ .format(self.__class__.__name__))
+ issue_deprecation_warning(
+ 'site parameter of CosmeticChangesToolkit',
+ 'a pywikibot.Page object as first parameter',
+ warning_class=FutureWarning,
+ since='20201102')
+ else:
+ if namespace is not None or pageTitle is not None:
+ raise TypeError(
+ "'namespace' and 'pageTitle' arguments are
invalid with "
+ 'a given Page object')
+ self.site = page.site
+ self.title = page.title()
+ self.namespace = page.namespace()
+
self.show_diff = show_diff
- try:
- self.namespace = self.site.namespaces.resolve(namespace).pop(0)
- except (KeyError, TypeError, IndexError):
- raise ValueError('{0} needs a valid namespace'
- .format(self.__class__.__name__))
self.template = (self.namespace == 10)
self.talkpage = self.namespace >= 0 and self.namespace % 2 == 1
- self.title = pageTitle
self.ignore = ignore
self.common_methods = [
@@ -258,11 +288,12 @@
self.show_diff = bool(value)
@classmethod
+ @deprecated('CosmeticChangesToolkit with pywikibot.Page object',
+ future_warning=True, since='20200415')
@deprecated_args(diff='show_diff')
def from_page(cls, page, show_diff=False, ignore=CANCEL_ALL):
"""Create toolkit based on the page."""
- return cls(page.site, show_diff=show_diff, namespace=page.namespace(),
- pageTitle=page.title(), ignore=ignore)
+ return cls(page, show_diff=show_diff, ignore=ignore)
def safe_execute(self, method, text):
"""Execute the method and catch exceptions if
enabled."""
diff --git a/pywikibot/page/__init__.py b/pywikibot/page/__init__.py
index 9ba81df..bf1f657 100644
--- a/pywikibot/page/__init__.py
+++ b/pywikibot/page/__init__.py
@@ -1303,9 +1303,7 @@
# cc depends on page directly and via several other imports
from pywikibot.cosmetic_changes import (
CANCEL_MATCH, CosmeticChangesToolkit)
- cc_toolkit = CosmeticChangesToolkit(
- self.site, namespace=self.namespace(), pageTitle=self.title(),
- ignore=CANCEL_MATCH)
+ cc_toolkit = CosmeticChangesToolkit(self, ignore=CANCEL_MATCH)
self.text = cc_toolkit.change(old)
if summary and old.strip().replace(
'\r\n', '\n') !=
self.text.strip().replace('\r\n', '\n'):
diff --git a/scripts/cosmetic_changes.py b/scripts/cosmetic_changes.py
index 7933990..02abc43 100644
--- a/scripts/cosmetic_changes.py
+++ b/scripts/cosmetic_changes.py
@@ -34,8 +34,12 @@
#
import pywikibot
-from pywikibot import config, cosmetic_changes, i18n, pagegenerators
+from pywikibot import config, i18n, pagegenerators
from pywikibot.bot import MultipleSitesBot, ExistingPageBot, NoRedirectPageBot
+from pywikibot.cosmetic_changes import (
+ CANCEL_ALL, CANCEL_MATCH, CANCEL_METHOD, CANCEL_PAGE,
+ CosmeticChangesToolkit,
+)
from pywikibot.tools import PYTHON_VERSION
if PYTHON_VERSION >= (3, 9):
@@ -65,7 +69,7 @@
self.available_options.update({
'async': False,
'summary': 'Robot: Cosmetic changes',
- 'ignore': cosmetic_changes.CANCEL_ALL,
+ 'ignore': CANCEL_ALL,
})
super().__init__(**kwargs)
@@ -73,8 +77,8 @@
def treat_page(self) -> None:
"""Treat page with the cosmetic toolkit."""
- cc_toolkit = cosmetic_changes.CosmeticChangesToolkit.from_page(
- self.current_page, ignore=self.opt.ignore)
+ cc_toolkit = CosmeticChangesToolkit(self.current_page,
+ ignore=self.opt.ignore)
changed_text = cc_toolkit.change(self.current_page.get())
if changed_text is not False:
self.put_current(new_text=changed_text,
@@ -106,11 +110,11 @@
elif arg.startswith('-ignore:'):
ignore_mode = arg[len('-ignore:'):].lower()
if ignore_mode == 'method':
- options['ignore'] = cosmetic_changes.CANCEL_METHOD
+ options['ignore'] = CANCEL_METHOD
elif ignore_mode == 'page':
- options['ignore'] = cosmetic_changes.CANCEL_PAGE
+ options['ignore'] = CANCEL_PAGE
elif ignore_mode == 'match':
- options['ignore'] = cosmetic_changes.CANCEL_MATCH
+ options['ignore'] = CANCEL_MATCH
else:
raise ValueError(
'Unknown ignore mode "{0}"!'.format(ignore_mode))
--
To view, visit
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/589016
To unsubscribe, or for help writing mail filters, visit
https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ic98fe7a01a221972c6474871679769a98240d99e
Gerrit-Change-Number: 589016
Gerrit-PatchSet: 5
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: D3r1ck01 <xsavitar.wiki(a)aol.com>
Gerrit-Reviewer: Hazard-SJ <hazardsjwiki(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged