jenkins-bot has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1311916?usp=email )

Change subject: IMPR: use new User.contribs with revertbot.py
......................................................................

IMPR: use new User.contribs with revertbot.py

Change-Id: I050e42e48922d334882abe0ccc0cd848b614f684
---
M scripts/revertbot.py
1 file changed, 101 insertions(+), 22 deletions(-)

Approvals:
  Xqt: Looks good to me, approved
  jenkins-bot: Verified




diff --git a/scripts/revertbot.py b/scripts/revertbot.py
index 371d232..6434c2a 100755
--- a/scripts/revertbot.py
+++ b/scripts/revertbot.py
@@ -18,46 +18,54 @@
 -limit:num  [int] Use the last num contributions to be checked for
             revert. Default is 500.

-Users who want to customize the behaviour should subclass the `BaseRevertBot`
-and override its `callback` method. Here is a sample:
+Users who want to customize the behaviour should subclass the
+`ContribRevertBot` and override its `callback` method. Here is a sample:

 .. code:: python

-    class myRevertBot(BaseRevertBot):
+    class myRevertBot(ContribRevertBot):

         '''Example revert bot.'''

-        def callback(self, item) -> bool:
+        def callback(self, item: page.Contribution) -> bool:
             '''Sample callback function for 'private' revert bot.

-            :param item: an item from user contributions
-            :type item: dict
+            :param item: an item from User.contribs
             '''
-            if 'top' in item:
-                page = pywikibot.Page(self.site, item['title'])
+            if item.top:
+                page = item.page
                 text = page.get(get_redirect=True)
                 pattern = re.compile(r'\[\[.+?:.+?\..+?\]\]')
                 return bool(pattern.search(text))
             return False
+
+.. version-changed:: 11.7
+   Contribution items are now :class:`page.Contribution` instances
+   instead of generic mappings. :class:`BaseRevertBot` and
+   :class:`myRevertBot` are kept for backward compatibility and use the
+   legacy data format.
 """
 from __future__ import annotations

-from collections.abc import Container
+import abc
+from collections.abc import Mapping
 from textwrap import fill
+from typing import Any

 import pywikibot
 from pywikibot import i18n
 from pywikibot.bot import OptionHandler
 from pywikibot.date import format_date, formatYear
 from pywikibot.exceptions import APIError, Error
+from pywikibot.page import Contribution
+from pywikibot.tools import deprecated


-class BaseRevertBot(OptionHandler):
+class AbstractRevertBot(OptionHandler, abc.ABC):

-    """Base revert bot.
+    """Abstract RevertBot class.

-    Subclass this bot and override callback to get it to do something
-    useful.
+    .. version-added:: 11.7
     """

     available_options = {
@@ -72,10 +80,10 @@
         self.user = kwargs.pop('user', self.site.username())
         super().__init__(**kwargs)

+    @abc.abstractmethod
     def get_contributions(self, total: int = 500, ns=None):
         """Get contributions."""
-        return self.site.usercontribs(user=self.user, namespaces=ns,
-                                      total=total)
+        ...

     def revert_contribs(self, callback=None) -> None:
         """Revert contributions."""
@@ -94,9 +102,10 @@
                 pywikibot.info(f"Skipped {item['title']} by callback")

     @staticmethod
-    def callback(item: Container) -> bool:
+    @abc.abstractmethod
+    def callback(item: Mapping[str, Any]) -> bool:
         """Callback function."""
-        return 'top' in item
+        ...

     def local_timestamp(self, ts) -> str:
         """Convert Timestamp to a localized timestamp string.
@@ -108,9 +117,14 @@
         *_, time = str(ts).strip('Z').partition('T')
         return f'{date} {year} {time}'

-    def revert(self, item) -> str | bool:
+    @abc.abstractmethod
+    def get_page(self, item: Mapping[str, Any]) -> pywikibot.Page:
+        """Get page from item."""
+        ...
+
+    def revert(self, item: Mapping[str, Any]) -> str | bool:
         """Revert a single item."""
-        page = pywikibot.Page(self.site, item['title'])
+        page = self.get_page(item)
         history = list(page.revisions(total=2))
         if len(history) <= 1:
             return False
@@ -153,8 +167,73 @@
         return False


-# for compatibility only
-myRevertBot = BaseRevertBot  # noqa: N816
+class BaseRevertBot(AbstractRevertBot):
+
+    """Legacy RevertBot class using dict-like contribution mappings.
+
+    .. version-deprecated:: 11.7
+       Use :class:`ContribRevertBot` instead.
+    """
+
+    @deprecated(since='11.7.0')
+    def __init__(self, site=None, **kwargs) -> None:
+        """Initializer."""
+        super().__init__(**kwargs)
+
+    def get_contributions(self, total: int = 500, ns=None):
+        """Get contributions."""
+        return self.site.usercontribs(user=self.user, namespaces=ns,
+                                      total=total)
+
+    def get_page(self, item: Mapping[str, Any]) -> pywikibot.Page:
+        """Get page from item."""
+        return pywikibot.Page(self.site, item['title'])
+
+    @staticmethod
+    def callback(item: Mapping[str, Any]) -> bool:
+        """Callback function.
+
+        .. note:: item is a dict like mapping.
+        """
+        return 'top' in item
+
+
+class ContribRevertBot(AbstractRevertBot):
+
+    """Base RevertBot class.
+
+    Subclass this bot and override callback to get it to do something
+    useful.
+
+    .. version-added:: 11.7
+    """
+
+    def get_contributions(self, total: int = 500, ns=None):
+        """Get contributions."""
+        user = pywikibot.User(self.site, self.user)
+        return user.contribs(namespaces=ns, total=total)
+
+    def get_page(self, item: Contribution) -> pywikibot.Page:
+        """Get page from item."""
+        return item.page
+
+    @staticmethod
+    def callback(item: Contribution) -> bool:
+        """Callback function.
+
+        .. note:: item is a :class:`Contribution` mapping.
+
+        :param item: the contribution information.
+        """
+        return item.top
+
+
+class myRevertBot(BaseRevertBot):  # noqa: N801
+
+    """Deprecated myRevertBot, for compatibility only.
+
+    .. version-deprecated:: 11.7
+    """


 def main(*args: str) -> None:
@@ -179,7 +258,7 @@
         elif opt == 'limit':
             options[opt] = int(value)

-    bot = myRevertBot(**options)
+    bot = ContribRevertBot(**options)
     bot.revert_contribs()



--
To view, visit 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1311916?usp=email
To unsubscribe, or for help writing mail filters, visit 
https://gerrit.wikimedia.org/r/settings?usp=email

Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I050e42e48922d334882abe0ccc0cd848b614f684
Gerrit-Change-Number: 1311916
Gerrit-PatchSet: 4
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to