jenkins-bot has submitted this change. (
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/633132 )
Change subject: [IMPR] Replace options item settings with opt attribute setting
......................................................................
[IMPR] Replace options item settings with opt attribute setting
Bot options item setting gives a FutureWarning
- replace all Bot.options item setting with new Bot.opt attribute
setting
- replace availableOptions with available_options in these files
- replace getOption method with opt attribute in these files
- shorten super calls
Change-Id: If4ddea1d37cd25541f977d4b34786cc10d3e27e3
---
M pywikibot/bot.py
M pywikibot/specialbots/_unlink.py
M scripts/commonscat.py
M scripts/djvutext.py
M scripts/interwikidata.py
M scripts/lonelypages.py
M scripts/newitem.py
M scripts/replace.py
M scripts/template.py
M scripts/wikisourcetext.py
10 files changed, 93 insertions(+), 108 deletions(-)
Approvals:
Hazard-SJ: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index 82cf842..3fe40ea 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -1216,7 +1216,7 @@
if choice == 'a':
# Remember the choice
- self.options['always'] = True
+ self.opt.always = True
return True
diff --git a/pywikibot/specialbots/_unlink.py b/pywikibot/specialbots/_unlink.py
index abd2e1d..b7e0732 100644
--- a/pywikibot/specialbots/_unlink.py
+++ b/pywikibot/specialbots/_unlink.py
@@ -47,7 +47,7 @@
def handle_answer(self, choice):
"""Handle choice and store in bot's options."""
answer = super().handle_answer(choice)
- self._bot.options['always'] = self._always.always
+ self._bot.opt.always = self._always.always
return answer
diff --git a/scripts/commonscat.py b/scripts/commonscat.py
index 5e01aae..5a58b2a 100755
--- a/scripts/commonscat.py
+++ b/scripts/commonscat.py
@@ -224,10 +224,10 @@
def __init__(self, **kwargs):
"""Initializer."""
- self.availableOptions.update({
+ self.available_options.update({
'summary': None,
})
- super(CommonscatBot, self).__init__(**kwargs)
+ super().__init__(**kwargs)
def skip_page(self, page):
"""Skip category redirects or disambigs."""
@@ -241,7 +241,7 @@
'Page {page} on {page.site} is a disambiguation. '
'Skipping.'.format(page=page))
return True
- return super(CommonscatBot, self).skip_page(page)
+ return super().skip_page(page)
def skipPage(self, page):
"""Determine if the page should be skipped."""
@@ -317,11 +317,11 @@
textToAdd = '{{%s|%s}}' % (primaryCommonscat,
commonscatLink)
result, _, always = add_text(page, textToAdd,
- self.getOption('summary'),
- always=self.getOption('always'))
+ self.opt.summary,
+ always=self.opt.always)
if result is True:
self._save_counter += 1
- self.options['always'] = always
+ self.opt.always = always
def changeCommonscat(
self, page=None, oldtemplate='', oldcat='',
@@ -350,8 +350,8 @@
page.get())
else: # nothing left to do
return
- if self.getOption('summary'):
- comment = self.getOption('summary')
+ if self.opt.summary:
+ comment = self.opt.summary
else:
comment = i18n.twtranslate(page.site,
'commonscat-msg_change',
diff --git a/scripts/djvutext.py b/scripts/djvutext.py
index 36427e4..1b30c64 100644
--- a/scripts/djvutext.py
+++ b/scripts/djvutext.py
@@ -62,7 +62,7 @@
@param pages: page interval to upload (start, end)
@type pages: tuple
"""
- self.availableOptions.update({
+ self.available_options.update({
'force': False,
'summary': None
})
@@ -80,9 +80,9 @@
self.generator = self.gen()
# Get edit summary message if it's empty.
- if not self.getOption('summary'):
- self.options['summary'] = i18n.twtranslate(
- self._index.site, 'djvutext-creating')
+ if not self.opt.summary:
+ self.opt.summary = i18n.twtranslate(self._index.site,
+ 'djvutext-creating')
def page_number_gen(self):
"""Generate pages numbers from specified page intervals."""
@@ -111,8 +111,8 @@
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
- summary = self.getOption('summary')
- if page.exists() and not self.getOption('force'):
+ summary = self.opt.summary
+ if page.exists() and not self.opt.force:
pywikibot.output(
'Page {} already exists, not adding!\n'
'Use -force option to overwrite the output page.'
diff --git a/scripts/interwikidata.py b/scripts/interwikidata.py
index 51518cc..f554420 100644
--- a/scripts/interwikidata.py
+++ b/scripts/interwikidata.py
@@ -51,7 +51,7 @@
def __init__(self, **kwargs) -> None:
"""Initialize the bot."""
- self.availableOptions.update({
+ self.available_options.update({
'clean': False,
'create': False,
'merge': False,
@@ -64,14 +64,14 @@
'use interwiki.py instead.'.format(
site=self.site))
self.repo = self.site.data_repository()
- if not self.getOption('summary'):
- self.options['summary'] = pywikibot.i18n.twtranslate(
+ if not self.opt.summary:
+ self.opt.summary = pywikibot.i18n.twtranslate(
self.site, 'interwikidata-clean-summary')
def treat_page(self) -> None:
"""Check page."""
if (self.current_page.namespace() not in NAMESPACES
- and not self.getOption('ignore_ns')):
+ and not self.opt.ignore_ns):
output('{page} is not in allowed namespaces, skipping'
.format(page=self.current_page.title(
as_link=True)))
@@ -89,13 +89,13 @@
if item is None:
item = self.try_to_add()
- if self.getOption('create') and item is None:
+ if self.opt.create and item is None:
item = self.create_item()
else:
- if self.getOption('merge'):
+ if self.opt.merge:
item = self.try_to_merge(item)
- if item and self.getOption('clean'):
+ if item and self.opt.clean:
self.current_item = item
self.clean_page()
@@ -151,7 +151,7 @@
output('Cleaning up the page')
new_text = pywikibot.textlib.removeLanguageLinks(
self.current_page.text, site=self.current_page.site)
- self.put_current(new_text, summary=self.getOption('summary'))
+ self.put_current(new_text, summary=self.opt.summary)
def get_items(self) -> Set[pywikibot.ItemPage]:
"""Return all items of pages linked through the interwiki."""
diff --git a/scripts/lonelypages.py b/scripts/lonelypages.py
index e09925a..e7f7d2e 100755
--- a/scripts/lonelypages.py
+++ b/scripts/lonelypages.py
@@ -98,17 +98,17 @@
def __init__(self, generator, **kwargs):
"""Initializer."""
- self.availableOptions.update({
+ self.available_options.update({
'enablePage': None, # Check if someone set an enablePage or not
'disambigPage': None, # If no disambigPage given, not use it.
})
- super(LonelyPagesBot, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.generator = generator
# Take the configurations according to our project
- if self.getOption('enablePage'):
- self.options['enablePage'] = pywikibot.Page(
- self.site, self.getOption('enablePage'))
+ if self.opt.enablePage:
+ self.opt.enablePage = pywikibot.Page(
+ self.site, self.opt.enablePage)
self.comment = i18n.twtranslate(
self.site, 'lonelypages-comment-add-template')
self.commentdisambig = i18n.twtranslate(
@@ -127,9 +127,9 @@
else:
self._settings = orphan_template
# DisambigPage part
- if self.getOption('disambigPage') is not None:
+ if self.opt.disambigPage is not None:
self.disambigpage = pywikibot.Page(
- self.site, self.getOption('disambigPage'))
+ self.site, self.opt.disambigPage)
try:
self.disambigtext = self.disambigpage.get()
except pywikibot.NoPage:
@@ -139,7 +139,7 @@
except pywikibot.IsRedirectPage:
pywikibot.output("{0} is a redirect, don't use it!"
.format(self.disambigpage.title()))
- self.options['disambigPage'] = None
+ self.opt.disambigPage = None
@property
def settings(self):
@@ -148,7 +148,7 @@
def enable_page(self):
"""Enable or disable bot via wiki page."""
- enable = self.getOption('enablePage')
+ enable = self.opt.enablePage
if enable is not None:
try:
getenable = enable.get()
@@ -204,7 +204,7 @@
.format(page.title()))
return
if (page.isDisambig()
- and self.getOption('disambigPage') is not None):
+ and self.opt.disambigPage is not None):
pywikibot.output('{0} is a disambig page, report..'
.format(page.title()))
if not page.title().lower() in self.disambigtext.lower():
diff --git a/scripts/newitem.py b/scripts/newitem.py
index a7b9436..e5dc763 100755
--- a/scripts/newitem.py
+++ b/scripts/newitem.py
@@ -46,8 +46,8 @@
treat_missing_item = True
def __init__(self, generator, **kwargs) -> None:
- """Only accepts options defined in availableOptions."""
- self.availableOptions.update({
+ """Only accepts options defined in available_options."""
+ self.available_options.update({
'always': True,
'lastedit': 7,
'pageage': 21,
@@ -57,8 +57,6 @@
super().__init__(**kwargs)
self.generator = generator
- self.pageAge = self.getOption('pageage')
- self.lastEdit = self.getOption('lastedit')
self._skipping_templates = {}
def setup(self) -> None:
@@ -66,16 +64,17 @@
super().setup()
self.pageAgeBefore = self.repo.server_time() - timedelta(
- days=self.pageAge)
+ days=self.opt.pageage)
self.lastEditBefore = self.repo.server_time() - timedelta(
- days=self.lastEdit)
- pywikibot.output('Page age is set to {0} days so only pages created'
- '\nbefore {1} will be considered.\n'
- .format(self.pageAge, self.pageAgeBefore.isoformat()))
+ days=self.opt.lastedit)
+ pywikibot.output('Page age is set to {} days so only pages created'
+ '\nbefore {} will be considered.\n'
+ .format(self.opt.pageage,
+ self.pageAgeBefore.isoformat()))
pywikibot.output(
- 'Last edit is set to {0} days so only pages last edited'
- '\nbefore {1} will be considered.\n'
- .format(self.lastEdit, self.lastEditBefore.isoformat()))
+ 'Last edit is set to {} days so only pages last edited'
+ '\nbefore {} will be considered.\n'
+ .format(self.opt.lastedit, self.lastEditBefore.isoformat()))
@staticmethod
def _touch_page(page) -> None:
@@ -93,7 +92,7 @@
page.title(as_link=True)))
def _callback(self, page, exc) -> None:
- if exc is None and self.getOption('touch'):
+ if exc is None and self.opt.touch:
self._touch_page(page)
def get_skipping_templates(self, site) -> Set[pywikibot.Page]:
@@ -177,7 +176,7 @@
if item and item.exists():
pywikibot.output('{0} already has an item: {1}.'
.format(page, item))
- if self.getOption('touch') is True:
+ if self.opt.touch is True:
self._touch_page(page)
return
@@ -217,8 +216,7 @@
if not bot.site.logged_in():
bot.site.login()
user = pywikibot.User(bot.site, bot.site.username())
- if bot.getOption('touch') == 'newly' \
- and 'autoconfirmed' not in user.groups():
+ if bot.opt.touch == 'newly' and 'autoconfirmed' not in user.groups():
pywikibot.warning(fill(
'You are logged in as {}, an account that is '
'not in the autoconfirmed group on {}. Script '
@@ -226,7 +224,7 @@
'items to avoid triggering edit rates or '
'captchas. Use -touch param to force this.'
.format(user.username, bot.site.sitename)))
- bot.options['touch'] = False
+ bot.opt.touch = False
bot.run()
diff --git a/scripts/replace.py b/scripts/replace.py
index 9106baa..97e2f57 100755
--- a/scripts/replace.py
+++ b/scripts/replace.py
@@ -529,7 +529,7 @@
@deprecated_args(acceptall='always', addedCat='addcat')
def __init__(self, generator, replacements, exceptions={}, **kwargs):
"""Initializer."""
- self.availableOptions.update({
+ self.available_options.update({
'addcat': None,
'allowoverlap': False,
'recursive': False,
@@ -550,12 +550,8 @@
self.replacements = replacements
self.exceptions = exceptions
- self.sleep = self.getOption('sleep')
- self.summary = self.getOption('summary')
-
- self.addcat = self.getOption('addcat')
- if self.addcat and isinstance(self.addcat, str):
- self.addcat = pywikibot.Category(self.site, self.addcat)
+ if self.opt.addcat and isinstance(self.opt.addcat, str):
+ self.opt.addcat = pywikibot.Category(self.site, self.opt.addcat)
self._pending_processed_titles = Queue()
@@ -595,8 +591,8 @@
exceptions = _get_text_exceptions(self.exceptions)
skipped_containers = set()
for replacement in self.replacements:
- if self.sleep:
- pywikibot.sleep(self.sleep)
+ if self.opt.sleep:
+ pywikibot.sleep(self.opt.sleep)
if (replacement.container
and replacement.container.name in skipped_containers):
continue
@@ -619,7 +615,7 @@
new_text = textlib.replaceExcept(
new_text, replacement.old_regex, replacement.new,
exceptions + replacement.get_inside_exceptions(),
- allowoverlap=self.getOption('allowoverlap'), site=self.site)
+ allowoverlap=self.opt.allowoverlap, site=self.site)
if old_text != new_text:
applied.add(replacement)
@@ -660,8 +656,8 @@
default_summaries.add((replacement.old, replacement.new))
summary_messages = sorted(summary_messages)
if default_summaries:
- if self.summary:
- summary_messages.insert(0, self.summary)
+ if self.opt.summary:
+ summary_messages.insert(0, self.opt.summary)
else:
comma = self.site.mediawiki_message('comma-separator')
default_summary = comma.join(
@@ -706,7 +702,7 @@
last_text = new_text
new_text = self.apply_replacements(last_text, applied,
page)
- if not self.getOption('recursive'):
+ if not self.opt.recursive:
break
if new_text == original_text:
@@ -714,12 +710,12 @@
+ page.title(as_link=True))
return
- if self.addcat:
+ if self.opt.addcat:
# Fetch only categories in wikitext, otherwise the others
# will be explicitly added.
cats = textlib.getCategoryLinks(new_text, site=page.site)
- if self.addcat not in cats:
- cats.append(self.addcat)
+ if self.opt.addcat not in cats:
+ cats.append(self.opt.addcat)
new_text = textlib.replaceCategoryLinks(new_text,
cats,
site=page.site)
@@ -727,8 +723,9 @@
# Highlight the title in purple.
self.current_page = page
pywikibot.showDiff(original_text, new_text, context=context)
- if self.getOption('always'):
+ if self.opt.always:
break
+
choice = pywikibot.input_choice(
'Do you want to accept these changes?',
[('Yes', 'y'), ('No', 'n'), ('Edit original', 'e'),
@@ -761,7 +758,7 @@
last_text = None
continue
if choice == 'a':
- self.options['always'] = True
+ self.opt.always = True
if choice == 'y':
self.save(page, original_text, new_text, applied,
show_diff=False, quiet=True,
@@ -775,7 +772,7 @@
# choice must be 'N'
break
- if self.getOption('always') and new_text != original_text:
+ if self.opt.always and new_text != original_text:
self.save(page, original_text, new_text, applied,
show_diff=False, asynchronous=False)
diff --git a/scripts/template.py b/scripts/template.py
index 2c18a7b..0dfa0bc 100755
--- a/scripts/template.py
+++ b/scripts/template.py
@@ -194,20 +194,18 @@
self.templates = templates
# get edit summary message if it's empty
- if not self.getOption('summary'):
+ if not self.opt.summary:
comma = self.site.mediawiki_message('comma-separator')
params = {'list': comma.join(self.templates.keys()),
'num': len(self.templates)}
- if self.getOption('remove'):
- self.options['summary'] = i18n.twtranslate(
- self.site, 'template-removing', params)
- elif self.getOption('subst'):
- self.options['summary'] = i18n.twtranslate(
- self.site, 'template-substituting', params)
+ if self.opt.remove:
+ tw_key = 'template-removing'
+ elif self.opt.subst:
+ tw_key = 'template-substituting'
else:
- self.options['summary'] = i18n.twtranslate(
- self.site, 'template-changing', params)
+ tw_key = 'template-changing'
+ self.opt.summary = i18n.twtranslate(self.site, tw_key, params)
replacements = []
exceptions = {}
@@ -215,18 +213,18 @@
for old, new in self.templates.items():
template_regex = builder.pattern(old)
- if self.getOption('subst') and self.getOption('remove'):
+ if self.opt.subst and self.opt.remove:
replacements.append((template_regex,
r'{{subst:%s\g<parameters>}}' % new))
exceptions['inside-tags'] = ['ref', 'gallery', 'poem',
'pagelist', ]
- elif self.getOption('subst'):
+ elif self.opt.subst:
replacements.append(
(template_regex, r'{{%s:%s\g<parameters>}}' %
- (self.getOption('subst'), old)))
+ (self.opt.subst, old)))
exceptions['inside-tags'] = ['ref', 'gallery', 'poem',
'pagelist', ]
- elif self.getOption('remove'):
+ elif self.opt.remove:
separate_line_regex = re.compile(
r'^[*#:]* *{0} *\n'.format(template_regex.pattern),
re.DOTALL | re.MULTILINE)
@@ -252,9 +250,9 @@
super().__init__(
generator, replacements, exceptions,
- always=self.getOption('always'),
- addcat=self.getOption('addcat'),
- summary=self.getOption('summary'))
+ always=self.opt.always,
+ addcat=self.opt.addcat,
+ summary=self.opt.summary)
def main(*args) -> None:
diff --git a/scripts/wikisourcetext.py b/scripts/wikisourcetext.py
index e496d9f..ba3d670 100644
--- a/scripts/wikisourcetext.py
+++ b/scripts/wikisourcetext.py
@@ -104,30 +104,28 @@
@param generator: page generator
@type generator: generator
"""
- self.availableOptions.update({
+ self.available_options.update({
'showdiff': False,
'force': False,
'ocr': False,
'summary': 'Bot: uploading text',
'threads': 5
})
- super(UploadTextBot, self).__init__(**kwargs)
+ super().__init__(**kwargs)
self.generator = generator
- # TODO: create i18 files
# Get edit summary message if it's empty.
- if not self.getOption('summary'):
- self.options['summary'] = i18n.twtranslate(self.site,
- 'djvutext-creating')
+ if not self.opt.summary:
+ self.opt.summary = i18n.twtranslate(self.site, 'djvutext-creating')
- if self.getOption('ocr'):
- self._num_threads = self.getOption('threads')
+ if self.opt.ocr:
+ self._num_threads = self.opt.threads
self._queue_in = queue.Queue()
self._queue_out = queue.PriorityQueue()
# If not "-force", no reason to get OCR for existing pages
# and to process them in Bot.run().
- if not self.getOption('force'):
+ if not self.opt.force:
self.generator = (p for p in self.generator if not p.exists())
self._spawn_ocr_threads()
@@ -151,7 +149,7 @@
while True:
page, idx = self._queue_in.get()
try:
- text_body = page.ocr(ocr_tool=self.getOption('ocr'))
+ text_body = page.ocr(ocr_tool=self.opt.ocr)
except ValueError as e:
# TODO: is it a problem in PY2?
pywikibot.error(str(e))
@@ -184,28 +182,22 @@
raise pywikibot.Error('Page {} must be a ProofreadPage object.'
.format(page))
- summary = self.getOption('summary')
-
- if page.exists():
- old_text = page.text
- else:
- old_text = ''
-
- if self.getOption('ocr'):
+ old_text = page.text if page.exists() else ''
+ if self.opt.ocr:
_body = self._get_ocr(page)
if _body is None:
pywikibot.output('No OCR found. Skipping {}'
.format(page.title(as_link=True)))
return
+
page.body = _body
- if (page.exists()
- and not (self.getOption('ocr') and self.getOption('force'))):
+ if page.exists() and not (self.opt.ocr and self.opt.force):
pywikibot.output('Page {} already exists, not adding!'
.format(page))
else:
- self.userPut(page, old_text, page.text, summary=summary,
- show_diff=self.getOption('showdiff'))
+ self.userPut(page, old_text, page.text, summary=self.opt.summary,
+ show_diff=self.opt.showdiff)
def main(*args):
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/633132
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: If4ddea1d37cd25541f977d4b34786cc10d3e27e3
Gerrit-Change-Number: 633132
Gerrit-PatchSet: 4
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: D3r1ck01 <[email protected]>
Gerrit-Reviewer: Hazard-SJ <[email protected]>
Gerrit-Reviewer: Meno25 <[email protected]>
Gerrit-Reviewer: jenkins-bot
Gerrit-CC: Mpaa <[email protected]>
Gerrit-MessageType: merged
_______________________________________________
Pywikibot-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/pywikibot-commits