Ladsgroup has submitted this change and it was merged.

Change subject: Use pagegenerators for clean_sandbox.py
......................................................................


Use pagegenerators for clean_sandbox.py

Bug: T87634
Change-Id: If6de6b1a3df60b762d8dc99f1310602eee61d03f
---
M scripts/clean_sandbox.py
1 file changed, 34 insertions(+), 79 deletions(-)

Approvals:
  John Vandenberg: Looks good to me, approved
  XZise: Looks good to me, but someone else must approve
  Ladsgroup: Looks good to me, approved

Objections:
  Xqt: There's a problem with this change, please improve



diff --git a/scripts/clean_sandbox.py b/scripts/clean_sandbox.py
index 9d42220..527da31 100755
--- a/scripts/clean_sandbox.py
+++ b/scripts/clean_sandbox.py
@@ -5,6 +5,10 @@
 
 This script understands the following command-line arguments:
 
+&params;
+
+Furthermore, the following command line parameters are supported:
+
     -hours:#       Use this parameter if to make the script repeat itself
                    after # hours. Hours can be defined as a decimal. 0.01
                    hours are 36 seconds; 0.1 are 6 minutes.
@@ -13,20 +17,6 @@
                    was made. If no parameter is given it takes it from
                    hours and limits it between 5 and 15 minutes.
                    The minimum delay time is 5 minutes.
-
-    -user          Use this parameter to run the script in the user name-
-                   space.
-                   > ATTENTION: on most wiki THIS IS FORBIDEN FOR BOTS ! <
-                   > (please talk with your admin first)                 <
-                   Since it is considered bad style to edit user page with-
-                   out permission, the 'user_sandboxTemplate' for given
-                   language has to be set-up (no fall-back will be used).
-                   All pages containing that template will get cleaned.
-                   Please be also aware that the rules when to clean the
-                   user sandbox differ from those for project sandbox.
-
-    -page          Run the bot on specific page, you can use this when
-                   you haven't configured clean_candbox for your wiki.
 
     -text          The text that substitutes in the sandbox, you can use this
                    when you haven't configured clean_candbox for your wiki.
@@ -51,9 +41,8 @@
 
 import time
 import datetime
-import sys
 import pywikibot
-from pywikibot import i18n, Bot
+from pywikibot import i18n, Bot, pagegenerators
 
 content = {
     'commons': u'{{Sandbox}}\n<!-- Please edit only below this line. -->',
@@ -143,12 +132,10 @@
     'zh': u'Project:沙盒',
 }
 
-user_content = {
-    'de': u'{{Benutzer:DrTrigonBot/Spielwiese}}',
-}
-
-user_sandboxTemplate = {
-    'de': u'User:DrTrigonBot/Spielwiese',
+# This is required for the text that is shown when you run this script
+# with the parameter -help.
+docuReplacements = {
+    '&params;':     pagegenerators.parameterHelp,
 }
 
 
@@ -161,9 +148,7 @@
         'no_repeat': True,
         'delay': None,
         'delay_td': None,
-        'user': False,
         'text': "",
-        'page': None,
         'summary': "",
     }
 
@@ -178,23 +163,19 @@
             self.availableOptions['delay_td'] = datetime.timedelta(minutes=d)
 
         self.site = pywikibot.Site()
-        if self.getOption('user'):
-            localSandboxTitle = i18n.translate(self.site,
-                                               user_sandboxTemplate)
-            localSandbox = pywikibot.Page(self.site, localSandboxTitle)
-            content.update(user_content)
-            sandboxTitle[self.site.code] = [item.title() for item in
-                                            localSandbox.getReferences(
-                                                onlyTemplateInclusion=True)]
-            if self.site.code not in user_sandboxTemplate:
-                content[self.site.code] = None
-                pywikibot.output(
-                    u'Not properly set-up to run in user namespace!')
-        if (not sandboxTitle.get(self.site.code) and not 
self.getOption('page')) or (not content.get(
-                self.site.code) and not self.getOption('text')):
-            pywikibot.output(u'This bot is not configured for the given site '
-                             u'(%s), exiting.' % self.site)
-            sys.exit(0)
+        if not content.get(self.site.code) and not self.getOption('text'):
+            pywikibot.error(u'No content is given for pages, exiting.')
+            raise RuntimeError
+        if not self.generator:
+            if self.site.code not in sandboxTitle:
+                pywikibot.error(u'No generator is given for this site'
+                                 u'(%s), exiting.' % self.site)
+                raise RuntimeError
+            local_sandbox_title = sandboxTitle[self.site.code]
+            if not isinstance(local_sandbox_title, list):
+                local_sandbox_title = [local_sandbox_title]
+            self.generator = [pywikibot.Page(self.site, page_name) for
+                              page_name in local_sandbox_title]
 
     def run(self):
         """Run bot."""
@@ -202,16 +183,7 @@
         while True:
             wait = False
             now = time.strftime("%d %b %Y %H:%M:%S (UTC)", time.gmtime())
-            if self.getOption('page'):
-                localSandboxTitle = self.getOption('page')
-            else:
-                localSandboxTitle = i18n.translate(self.site, sandboxTitle)
-            if isinstance(localSandboxTitle, list):
-                titles = localSandboxTitle
-            else:
-                titles = [localSandboxTitle]
-            for title in titles:
-                sandboxPage = pywikibot.Page(self.site, title)
+            for sandboxPage in self.generator:
                 pywikibot.output(u'Preparing to process sandbox page %s'
                                  % sandboxPage.title(asLink=True))
                 if sandboxPage.isRedirectPage():
@@ -239,22 +211,10 @@
                         pywikibot.output(
                             u'The sandbox might be clean, no change 
necessary.')
                     elif pos != 0 and not subst:
-                        if self.getOption('user'):
-                            endpos = pos + len(translatedContent.strip())
-                            if (pos < 0) or (endpos == len(text)):
-                                pywikibot.output(u'The user sandbox is still '
-                                                 u'clean, no change 
necessary.')
-                            else:
-                                sandboxPage.put(text[:endpos], translatedMsg)
-                                pywikibot.showDiff(text, text[:endpos])
-                                pywikibot.output(
-                                    u'Standard content was changed, user '
-                                    u'sandbox cleaned.')
-                        else:
-                            sandboxPage.put(translatedContent, translatedMsg)
-                            pywikibot.showDiff(text, translatedContent)
-                            pywikibot.output(u'Standard content was changed, '
-                                             u'sandbox cleaned.')
+                        sandboxPage.put(translatedContent, translatedMsg)
+                        pywikibot.showDiff(text, translatedContent)
+                        pywikibot.output(u'Standard content was changed, '
+                                         u'sandbox cleaned.')
                     else:
                         edit_delta = (datetime.datetime.utcnow() -
                                       sandboxPage.editTime())
@@ -303,36 +263,31 @@
     @type args: list of unicode
     """
     opts = {}
-    for arg in pywikibot.handle_args(args):
+    local_args = pywikibot.handle_args(args)
+    gen_factory = pagegenerators.GeneratorFactory()
+    for arg in local_args:
         if arg.startswith('-hours:'):
             opts['hours'] = float(arg[7:])
             opts['no_repeat'] = False
         elif arg.startswith('-delay:'):
             opts['delay'] = int(arg[7:])
-        elif arg.startswith('-page'):
-            if len(arg) == 5:
-                opts['page'] = pywikibot.input(
-                    u'Which page do you want to change?')
-            else:
-                opts['page'] = arg[6:]
         elif arg.startswith('-text'):
             if len(arg) == 5:
                 opts['text'] = pywikibot.input(
                     u'What text do you want to substitute?')
             else:
                 opts['text'] = arg[6:]
-        elif arg == '-user':
-            opts['user'] = True
         elif arg.startswith('-summary'):
             if len(arg) == len('-summary'):
                 opts['summary'] = pywikibot.input(u'Enter the summary:')
             else:
                 opts['summary'] = arg[9:]
         else:
-            pywikibot.showHelp('clean_sandbox')
-            return
+            gen_factory.handleArg(arg)
 
-    bot = SandboxBot(**opts)
+    generator = gen_factory.getCombinedGenerator()
+
+    bot = SandboxBot(generator=generator, **opts)
     bot.run()
 
 if __name__ == "__main__":

-- 
To view, visit https://gerrit.wikimedia.org/r/210174
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: If6de6b1a3df60b762d8dc99f1310602eee61d03f
Gerrit-PatchSet: 7
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Ladsgroup <[email protected]>
Gerrit-Reviewer: John Vandenberg <[email protected]>
Gerrit-Reviewer: Ladsgroup <[email protected]>
Gerrit-Reviewer: Merlijn van Deen <[email protected]>
Gerrit-Reviewer: XZise <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot <>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to