Ricordisamoa has uploaded a new change for review.
https://gerrit.wikimedia.org/r/152841
Change subject: replace Bot.getOption() with 'options' property
......................................................................
replace Bot.getOption() with 'options' property
Bot._options is a new variable of OptionsDict type
(subclass of dict for internal use), which allows to get and set
bot options with the same 'options' property.
The standard 'update' method of the dict class has also been
subclassed in OptionsDict, and replaces the Bot.setOptions() method.
Every use of getOption() in scripts has been replaced.
Change-Id: Ia26b64bcab49a89dd907de6ba5cabb4d8ed3bb76
---
M pywikibot/bot.py
M scripts/capitalize_redirects.py
M scripts/clean_sandbox.py
M scripts/commons_link.py
M scripts/cosmetic_changes.py
M scripts/delete.py
M scripts/featured.py
M scripts/image.py
M scripts/isbn.py
M scripts/lonelypages.py
M scripts/movepages.py
M scripts/newitem.py
M scripts/noreferences.py
M scripts/nowcommons.py
M scripts/pagefromfile.py
M scripts/reflinks.py
M scripts/selflink.py
M scripts/template.py
M scripts/touch.py
M scripts/unlink.py
20 files changed, 158 insertions(+), 136 deletions(-)
git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core
refs/changes/41/152841/1
diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index 41cdb39..8f1804a 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -787,7 +787,43 @@
@param kwargs: bot options
@type kwargs: dict
"""
- self.setOptions(**kwargs)
+ bot = self
+
+ class OptionsDict(dict):
+ def __getitem__(self, option):
+ """
+ Get the current value of an option.
+
+ @param option: key defined in Bot.availableOptions
+ """
+ try:
+ return bot.options.get(option,
bot.availableOptions[option])
+ except KeyError:
+ raise pywikibot.Error(u'%s is not a valid bot option.' %
option)
+
+ def update(self, **kwargs):
+ """
+ Set the instance options.
+
+ @kwargs: options
+ """
+ validOptions = set(bot.availableOptions)
+ receivedOptions = set(kwargs)
+
+ for opt in receivedOptions & validOptions:
+ self[opt] = kwargs[opt]
+
+ for opt in receivedOptions - validOptions:
+ pywikibot.warning(u'%s is not a valid option. It was
ignored.'
+ % opt)
+
+ self._options = OptionsDict()
+ self.options.update(**kwargs)
+
+ @property
+ def options(self):
+ """Hold the options overriden from defaults."""
+ return self._options
def setOptions(self, **kwargs):
"""
@@ -796,18 +832,7 @@
@param kwargs: options
@type kwargs: dict
"""
- # contains the options overriden from defaults
- self.options = {}
-
- validOptions = set(self.availableOptions)
- receivedOptions = set(kwargs)
-
- for opt in receivedOptions & validOptions:
- self.options[opt] = kwargs[opt]
-
- for opt in receivedOptions - validOptions:
- pywikibot.warning(u'%s is not a valid option. It was ignored.'
- % opt)
+ self.options.update(**kwargs)
def getOption(self, option):
"""
@@ -815,10 +840,7 @@
@param option: key defined in Bot.availableOptions
"""
- try:
- return self.options.get(option, self.availableOptions[option])
- except KeyError:
- raise pywikibot.Error(u'%s is not a valid bot option.' % option)
+ return self.options[option]
def userPut(self, page, oldtext, newtext, **kwargs):
"""
@@ -838,7 +860,7 @@
pywikibot.showDiff(oldtext, newtext)
choice = 'a'
- if not self.getOption('always'):
+ if not self.options['always']:
choice = pywikibot.inputChoice(
u'Do you want to accept these changes?',
['Yes', 'No', 'All'],
diff --git a/scripts/capitalize_redirects.py b/scripts/capitalize_redirects.py
index 814d771..38350ce 100644
--- a/scripts/capitalize_redirects.py
+++ b/scripts/capitalize_redirects.py
@@ -61,7 +61,7 @@
# Highlight the title in purple.
pywikibot.output(u"\n>>> \03{lightpurple}%s\03{default} <<<"
% page_t)
- if self.getOption('titlecase'):
+ if self.options['titlecase']:
page_cap = pywikibot.Page(page.site, page_t.title())
else:
page_cap = pywikibot.Page(page.site, page_t.capitalize())
@@ -71,7 +71,7 @@
else:
pywikibot.output(u'%s doesn\'t exist'
% page_cap.title(asLink=True))
- if not self.getOption('always'):
+ if not self.options['always']:
choice = pywikibot.inputChoice(
u'Do you want to create a redirect?',
['Yes', 'No', 'All', 'Quit'], ['y', 'N', 'a', 'q'], 'N')
@@ -79,7 +79,7 @@
self.options['always'] = True
elif choice == 'q':
self.done = True
- if self.getOption('always') or choice == 'y':
+ if self.options['always'] or choice == 'y':
comment = i18n.twtranslate(
page.site,
'capitalize_redirects-create-redirect',
diff --git a/scripts/clean_sandbox.py b/scripts/clean_sandbox.py
index 6bfaecc..bcd9a14 100755
--- a/scripts/clean_sandbox.py
+++ b/scripts/clean_sandbox.py
@@ -150,16 +150,16 @@
def __init__(self, **kwargs):
super(SandboxBot, self).__init__(**kwargs)
- if self.getOption('delay') is None:
- d = min(15, max(5, int(self.getOption('hours') * 60)))
+ if self.options['delay'] is None:
+ d = min(15, max(5, int(self.options['hours'] * 60)))
self.availableOptions['delay_td'] = datetime.timedelta(minutes=d)
else:
- d = max(5, self.getOption('delay'))
+ d = max(5, self.options['delay'])
self.availableOptions['delay_td'] = datetime.timedelta(minutes=d)
self.site = pywikibot.Site()
self.site.login()
- if self.getOption('user'):
+ if self.options['user']:
localSandboxTitle = i18n.translate(self.site,
user_sandboxTemplate)
localSandbox = pywikibot.Page(self.site, localSandboxTitle)
@@ -171,8 +171,8 @@
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')):
+ if (not sandboxTitle.get(self.site.code) and not self.options['page'])
or (not content.get(
+ self.site.code) and not self.options['text']):
pywikibot.output(u'This bot is not configured for the given site '
u'(%s), exiting.' % self.site)
sys.exit(0)
@@ -181,8 +181,8 @@
while True:
wait = False
now = time.strftime("%d %b %Y %H:%M:%S (UTC)", time.gmtime())
- if self.getOption('page'):
- localSandboxTitle = self.getOption('page')
+ if self.options['page']:
+ localSandboxTitle = self.options['page']
else:
localSandboxTitle = i18n.translate(self.site, sandboxTitle)
if isinstance(localSandboxTitle, list):
@@ -199,12 +199,12 @@
% sandboxPage.title(asLink=True))
try:
text = sandboxPage.text
- if not self.getOption('text'):
+ if not self.options['text']:
translatedContent = i18n.translate(self.site, content)
else:
- translatedContent = self.getOption('text')
- if self.getOption('summary'):
- translatedMsg = self.getOption('summary')
+ translatedContent = self.options['text']
+ if self.options['summary']:
+ translatedMsg = self.options['summary']
else:
translatedMsg = i18n.twtranslate(
self.site, 'clean_sandbox-cleaned')
@@ -218,7 +218,7 @@
pywikibot.output(
u'The sandbox might be clean, no change
necessary.')
elif pos != 0 and not subst:
- if self.getOption('user'):
+ if self.options['user']:
endpos = pos + len(translatedContent.strip())
if (pos < 0) or (endpos == len(text)):
pywikibot.output(u'The user sandbox is still '
@@ -237,7 +237,7 @@
else:
edit_delta = (datetime.datetime.utcnow() -
sandboxPage.editTime())
- delta = self.getOption('delay_td') - edit_delta
+ delta = self.options['delay_td'] - edit_delta
# Is the last edit more than 'delay' minutes ago?
if delta <= datetime.timedelta(0):
sandboxPage.put(translatedContent, translatedMsg)
@@ -259,17 +259,17 @@
pywikibot.output(
u'*** The sandbox is not existent, skipping.')
continue
- if self.getOption('no_repeat'):
+ if self.options['no_repeat']:
pywikibot.output(u'\nDone.')
return
elif not wait:
- if self.getOption('hours') < 1.0:
+ if self.options['hours'] < 1.0:
pywikibot.output('\nSleeping %s minutes, now %s'
- % ((self.getOption('hours') * 60), now))
+ % ((self.options['hours'] * 60), now))
else:
pywikibot.output('\nSleeping %s hours, now %s'
- % (self.getOption('hours'), now))
- time.sleep(self.getOption('hours') * 60 * 60)
+ % (self.options['hours'], now))
+ time.sleep(self.options['hours'] * 60 * 60)
def main():
diff --git a/scripts/commons_link.py b/scripts/commons_link.py
index ec761ce..e666590 100644
--- a/scripts/commons_link.py
+++ b/scripts/commons_link.py
@@ -55,9 +55,9 @@
self.findTemplate3 = re.compile(ur'\{\{[Cc]ommons')
def run(self):
- if not all((self.getOption('action'), self.generator)):
+ if not all((self.options['action'], self.generator)):
return
- catmode = (self.getOption('action') == 'categories')
+ catmode = (self.options['action'] == 'categories')
for page in self.generator:
try:
pywikibot.output(u'\n>>>> %s <<<<' % page.title())
diff --git a/scripts/cosmetic_changes.py b/scripts/cosmetic_changes.py
index 90c0918..3ab3a7b 100755
--- a/scripts/cosmetic_changes.py
+++ b/scripts/cosmetic_changes.py
@@ -860,7 +860,7 @@
pageTitle=page.title())
changedText = ccToolkit.change(page.get())
self.userPut(page, page.text, changedText, comment=self.comment,
- async=self.getOption('async'))
+ async=self.options['async'])
except pywikibot.NoPage:
pywikibot.output("Page %s does not exist?!"
% page.title(asLink=True))
diff --git a/scripts/delete.py b/scripts/delete.py
index 8b023ac..f992824 100644
--- a/scripts/delete.py
+++ b/scripts/delete.py
@@ -69,10 +69,10 @@
"""
for page in self.generator:
pywikibot.output(u'Processing page %s' % page.title())
- if self.getOption('undelete'):
+ if self.options['undelete']:
page.undelete(self.summary)
else:
- page.delete(self.summary, not self.getOption('always'))
+ page.delete(self.summary, not self.options['always'])
def main():
diff --git a/scripts/featured.py b/scripts/featured.py
index 9e25425..25c9343 100644
--- a/scripts/featured.py
+++ b/scripts/featured.py
@@ -232,13 +232,13 @@
self.repo = self.site.data_repository()
# if no source site is given, give up
- if self.getOption('fromlang') is True:
+ if self.options['fromlang'] is True:
self.options['fromlang'] = False
# setup tasks running
self.tasks = []
for task in ('featured', 'good', 'lists', 'former'):
- if self.getOption(task):
+ if self.options[task]:
self.tasks.append(task)
if not self.tasks:
self.tasks = ['featured']
@@ -267,10 +267,10 @@
generator = _generator()
- if self.getOption('fromall'):
+ if self.options['fromall']:
return generator
- elif self.getOption('fromlang'):
- fromlang = self.getOption('fromlang')
+ elif self.options['fromlang']:
+ fromlang = self.options['fromlang']
if len(fromlang) == 1 and fromlang[0].find("--") >= 0:
start, end = fromlang[0].split("--", 1)
if not start:
@@ -300,7 +300,7 @@
return True
def readcache(self, task):
- if self.getOption('count') or self.getOption('nocache') is True:
+ if self.options['count'] or self.options['nocache'] is True:
return
self.filename = pywikibot.config.datafilepath("cache", task)
try:
@@ -313,9 +313,9 @@
pywikibot.output(u'Cache file %s not found.' % self.filename)
def writecache(self):
- if self.getOption('count'):
+ if self.options['count']:
return
- if not self.getOption('nocache') is True:
+ if not self.options['nocache'] is True:
pywikibot.output(u'Writing %d items to cache file %s.'
% (len(self.cache), self.filename))
f = open(self.filename, "wb")
@@ -379,7 +379,7 @@
% (site, len(articles), task))
while articles:
p = articles.pop(0)
- if p.title() < self.getOption('afterpage'):
+ if p.title() < self.options['afterpage']:
continue
if u"/" in p.title() and p.namespace() != 0:
@@ -393,7 +393,7 @@
yield p
def findTranslated(self, page, oursite=None):
- quiet = self.getOption('quiet')
+ quiet = self.options['quiet']
if not oursite:
oursite = self.site
if page.isRedirectPage():
@@ -506,12 +506,12 @@
if tosite.code not in self.cache[fromsite.code]:
self.cache[fromsite.code][tosite.code] = {}
cc = self.cache[fromsite.code][tosite.code]
- if self.getOption('nocache') is True or \
- fromsite.code in self.getOption('nocache'):
+ if self.options['nocache'] is True or \
+ fromsite.code in self.options['nocache']:
cc = {}
gen = self.featuredArticles(fromsite, task, cc)
- if self.getOption('count'):
+ if self.options['count']:
next(gen, None)
return # count only, we are ready here
gen = PreloadingGenerator(gen)
@@ -548,7 +548,7 @@
m1 = add_tl and re_Link_add.search(text)
m2 = remove_tl and re_Link_remove.search(text)
changed = False
- interactive = self.getOption('interactive')
+ interactive = self.options['interactive']
if add_tl:
if m1:
pywikibot.output(u"(already added)")
@@ -558,7 +558,7 @@
pywikibot.input(
u'Connecting %s -> %s. Proceed? [Y/N]'
% (source.title(), dest.title())) in ['Y', 'y']):
- if self.getOption('side'):
+ if self.options['side']:
# Placing {{Link FA|xx}} right next to
# corresponding interwiki
text = (text[:m1.end()] +
diff --git a/scripts/image.py b/scripts/image.py
index 3189d71..8f4b331 100644
--- a/scripts/image.py
+++ b/scripts/image.py
@@ -119,7 +119,7 @@
self.old_image = old_image
self.new_image = new_image
- if not self.getOption('summary'):
+ if not self.options['summary']:
if self.new_image:
self.options['summary'] = i18n.translate(self.site,
self.msg_replace,
fallback=True) \
@@ -150,13 +150,13 @@
# Be careful, spaces and _ have been converted to '\ ' and '\_'
escaped = re.sub('\\\\[_ ]', '[_ ]', escaped)
- if not self.getOption('loose') or not self.new_image:
+ if not self.options['loose'] or not self.new_image:
image_regex = re.compile(r'\[\[ *(?:' +
'|'.join(self.site.namespace(6, all=True)) + ')\s*:\s*' + escaped + '
*(?P<parameters>\|[^\n]+|) *\]\]')
else:
image_regex = re.compile(r'' + escaped)
if self.new_image:
- if not self.getOption('loose'):
+ if not self.options['loose']:
replacements.append((image_regex, '[[' +
self.site.image_namespace() + ':' + self.new_image + '\g<parameters>]]'))
else:
replacements.append((image_regex, self.new_image))
@@ -164,8 +164,8 @@
replacements.append((image_regex, ''))
replaceBot = replace.ReplaceRobot(self.generator, replacements,
- acceptall=self.getOption('always'),
- summary=self.getOption('summary'))
+ acceptall=self.options['always'],
+ summary=self.options['summary'])
replaceBot.run()
diff --git a/scripts/isbn.py b/scripts/isbn.py
index 6664394..9cf10f6 100755
--- a/scripts/isbn.py
+++ b/scripts/isbn.py
@@ -1398,10 +1398,10 @@
pywikibot.output(e)
newText = oldText
- if self.getOption('to13'):
+ if self.options['to13']:
newText = self.isbnR.sub(_isbn10toIsbn13, newText)
- if self.getOption('format'):
+ if self.options['format']:
newText = self.isbnR.sub(_hyphenateIsbnNumber, newText)
try:
self.userPut(page, page.text, newText, comment=self.comment)
diff --git a/scripts/lonelypages.py b/scripts/lonelypages.py
index 95b51fb..fbf9187 100644
--- a/scripts/lonelypages.py
+++ b/scripts/lonelypages.py
@@ -86,9 +86,9 @@
# Take the configurations according to our project
self.site = pywikibot.Site()
- if self.getOption('enablePage'):
+ if self.options['enablePage']:
self.options['enablePage'] = pywikibot.Page(
- self.site, self.getOption('enablePage'))
+ self.site, self.options['enablePage'])
self.comment = i18n.twtranslate(
self.site, 'lonelypages-comment-add-template')
self.commentdisambig = i18n.twtranslate(
@@ -99,8 +99,8 @@
pywikibot.showHelp()
sys.exit(u'Missing configuration for site %s' % self.site)
# DisambigPage part
- if self.getOption('disambigPage') is not None:
- self.disambigpage = pywikibot.Page(self.site,
self.getOption('disambigPage'))
+ if self.options['disambigPage'] is not None:
+ self.disambigpage = pywikibot.Page(self.site,
self.options['disambigPage'])
try:
self.disambigtext = self.disambigpage.get()
except pywikibot.NoPage:
@@ -112,7 +112,7 @@
self.options['disambigPage'] = None
def enable_page(self):
- enable = self.getOption('enablePage')
+ enable = self.options['enablePage']
if enable is not None:
try:
getenable = enable.get()
@@ -169,7 +169,7 @@
break
else:
return
- if page.isDisambig() and self.getOption('disambigPage') is not
None:
+ if page.isDisambig() and self.options['disambigPage'] is not None:
pywikibot.output(u'%s is a disambig page, report..'
% page.title())
if not page.title().lower() in self.disambigtext.lower():
diff --git a/scripts/movepages.py b/scripts/movepages.py
index e5329a1..80360fb 100644
--- a/scripts/movepages.py
+++ b/scripts/movepages.py
@@ -71,14 +71,14 @@
def moveOne(self, page, newPageTitle):
try:
- msg = self.getOption('summary')
+ msg = self.options['summary']
if not msg:
msg = i18n.twtranslate(page.site, 'movepages-moving')
pywikibot.output(u'Moving page %s to [[%s]]'
% (page.title(asLink=True),
newPageTitle))
- page.move(newPageTitle, reason=msg,
movetalkpage=self.getOption('movetalkpage'),
- deleteAndMove=self.getOption('noredirect'))
+ page.move(newPageTitle, reason=msg,
movetalkpage=self.options['movetalkpage'],
+ deleteAndMove=self.options['noredirect'])
except pywikibot.NoPage:
pywikibot.output(u'Page %s does not exist!' % page.title())
except pywikibot.IsRedirectPage:
@@ -94,7 +94,7 @@
# Highlight the title in purple.
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% page.title())
- if self.getOption('skipredirects') and page.isRedirectPage():
+ if self.options['skipredirects'] and page.isRedirectPage():
pywikibot.output(u'Page %s is a redirect; skipping.' %
page.title())
return
pagetitle = page.title(withNamespace=False)
@@ -108,10 +108,10 @@
newPageTitle = self.regex.sub(self.replacePattern, pagetitle)
if not self.noNamespace and namesp:
newPageTitle = (u'%s:%s' % (namesp, newPageTitle))
- if self.getOption('prefix'):
- newPageTitle = (u'%s%s' % (self.getOption('prefix'), pagetitle))
- if self.getOption('prefix') or self.appendAll or self.regexAll:
- if not self.getOption('always'):
+ if self.options['prefix']:
+ newPageTitle = (u'%s%s' % (self.options['prefix'], pagetitle))
+ if self.options['prefix'] or self.appendAll or self.regexAll:
+ if not self.options['always']:
choice2 = pywikibot.inputChoice(
u'Change the page title to "%s"?' % newPageTitle,
['yes', 'no', 'all', 'quit'], ['y', 'n', 'a', 'q'])
diff --git a/scripts/newitem.py b/scripts/newitem.py
index eefcf4b..afa013a 100644
--- a/scripts/newitem.py
+++ b/scripts/newitem.py
@@ -46,8 +46,8 @@
super(NewItemRobot, self).__init__(**kwargs)
self.generator = pagegenerators.PreloadingGenerator(generator)
self.repo = pywikibot.Site().data_repository()
- self.pageAge = self.getOption('pageage')
- self.lastEdit = self.getOption('lastedit')
+ self.pageAge = self.options['pageage']
+ self.lastEdit = self.options['lastedit']
self.pageAgeBefore = self.repo.getcurrenttime() -
timedelta(days=self.pageAge)
self.lastEditBefore = self.repo.getcurrenttime() -
timedelta(days=self.lastEdit)
@@ -69,7 +69,7 @@
item = pywikibot.ItemPage.fromPage(page)
if item.exists():
pywikibot.output(u'%s already has an item: %s.' % (page, item))
- if self.getOption('touch'):
+ if self.options['touch']:
pywikibot.output(u'Doing a null edit on the page.')
page.put(page.text)
elif page.isRedirectPage():
diff --git a/scripts/noreferences.py b/scripts/noreferences.py
index 718a47d..cc826ef 100755
--- a/scripts/noreferences.py
+++ b/scripts/noreferences.py
@@ -482,22 +482,22 @@
oldTextCleaned = pywikibot.removeDisabledParts(text)
if self.referencesR.search(oldTextCleaned) or \
self.referencesTagR.search(oldTextCleaned):
- if self.getOption('verbose'):
+ if self.options['verbose']:
pywikibot.output(u'No changes necessary: references tag
found.')
return False
elif self.referencesTemplates:
templateR = u'{{(' + u'|'.join(self.referencesTemplates) + ')'
if re.search(templateR, oldTextCleaned, re.IGNORECASE |
re.UNICODE):
- if self.getOption('verbose'):
+ if self.options['verbose']:
pywikibot.output(
u'No changes necessary: references template found.')
return False
if not self.refR.search(oldTextCleaned):
- if self.getOption('verbose'):
+ if self.options['verbose']:
pywikibot.output(u'No changes necessary: no ref tags found.')
return False
else:
- if self.getOption('verbose'):
+ if self.options['verbose']:
pywikibot.output(u'Found ref without references.')
return True
diff --git a/scripts/nowcommons.py b/scripts/nowcommons.py
index 19de9ac..676d0c9 100644
--- a/scripts/nowcommons.py
+++ b/scripts/nowcommons.py
@@ -261,7 +261,7 @@
break
def getPageGenerator(self):
- if self.getOption('use_hash'):
+ if self.options['use_hash']:
gen = self.useHashGenerator()
else:
nowCommonsTemplates = [pywikibot.Page(self.site, title,
@@ -309,7 +309,7 @@
comment = i18n.translate(self.site, nowCommonsMessage, fallback=True)
for page in self.getPageGenerator():
- if self.getOption('use_hash'):
+ if self.options['use_hash']:
# Page -> Has the namespace | commons image -> Not
images_list = page # 0 -> local image, 1 -> commons image
page = pywikibot.Page(self.site, images_list[0])
@@ -325,18 +325,18 @@
pywikibot.output(u'File is already on Commons.')
continue
md5 = localImagePage.getFileMd5Sum()
- if self.getOption('use_hash'):
+ if self.options['use_hash']:
filenameOnCommons = images_list[1]
else:
filenameOnCommons = self.findFilenameOnCommons(
localImagePage)
- if not filenameOnCommons and not self.getOption('use_hash'):
+ if not filenameOnCommons and not self.options['use_hash']:
pywikibot.output(u'NowCommons template not found.')
continue
commonsImagePage = pywikibot.ImagePage(commons, 'Image:%s'
% filenameOnCommons)
if localImagePage.title(withNamespace=False) == \
- commonsImagePage.title(withNamespace=False) and
self.getOption('use_hash'):
+ commonsImagePage.title(withNamespace=False) and
self.options['use_hash']:
pywikibot.output(
u'The local and the commons images have the same name')
if localImagePage.title(withNamespace=False) != \
@@ -347,7 +347,7 @@
u'\"\03{lightred}%s\03{default}\" is still used in
%i pages.'
% (localImagePage.title(withNamespace=False),
len(usingPages)))
- if self.getOption('replace') is True:
+ if self.options['replace'] is True:
pywikibot.output(
u'Replacing
\"\03{lightred}%s\03{default}\" by \
\"\03{lightgreen}%s\03{default}\".'
@@ -357,14 +357,14 @@
pg.FileLinksGenerator(localImagePage),
localImagePage.title(withNamespace=False),
commonsImagePage.title(withNamespace=False),
- '', self.getOption('replacealways'),
- self.getOption('replaceloose'))
+ '', self.options['replacealways'],
+ self.options['replaceloose'])
oImageRobot.run()
# If the image is used with the urlname the
# previous function won't work
if len(list(pywikibot.ImagePage(self.site,
page.title()).usingPages())) > 0 and \
-
self.getOption('replaceloose'):
+
self.options['replaceloose']:
oImageRobot = image.ImageRobot(
pg.FileLinksGenerator(
localImagePage),
@@ -372,13 +372,13 @@
withNamespace=False, asUrl=True),
commonsImagePage.title(
withNamespace=False),
- '', self.getOption('replacealways'),
- self.getOption('replaceloose'))
+ '', self.options['replacealways'],
+ self.options['replaceloose'])
oImageRobot.run()
# refresh because we want the updated list
usingPages = len(list(pywikibot.ImagePage(
self.site, page.title()).usingPages()))
- if usingPages > 0 and
self.getOption('use_hash'):
+ if usingPages > 0 and self.options['use_hash']:
# just an enter
pywikibot.input(
u'There are still %s pages with this \
@@ -393,17 +393,17 @@
u'No page is using
\"\03{lightgreen}%s\03{default}\" anymore.'
% localImagePage.title(withNamespace=False))
commonsText = commonsImagePage.get()
- if self.getOption('replaceonly') is False:
+ if self.options['replaceonly'] is False:
if md5 == commonsImagePage.getFileMd5Sum():
pywikibot.output(
u'The image is identical to the one on Commons.')
- if len(localImagePage.getFileVersionHistory()) > 1 and
not self.getOption('use_hash'):
+ if len(localImagePage.getFileVersionHistory()) > 1 and
not self.options['use_hash']:
pywikibot.output(
u"This image has a version history. Please \
delete it manually after making sure that the \
old versions are not worth keeping.""")
continue
- if self.getOption('always') is False:
+ if self.options['always'] is False:
pywikibot.output(
u'\n\n>>>> Description on
\03{lightpurple}%s\03{default} <<<<\n'
% page.title())
diff --git a/scripts/pagefromfile.py b/scripts/pagefromfile.py
index 221065e..8bff584 100644
--- a/scripts/pagefromfile.py
+++ b/scripts/pagefromfile.py
@@ -93,8 +93,8 @@
pywikibot.output(u">>> \03{lightpurple}%s\03{default} <<<"
% page.title())
- if self.getOption('summary'):
- comment = self.getOption('summary')
+ if self.options['summary']:
+ comment = self.options['summary']
else:
comment = i18n.twtranslate(mysite, 'pagefromfile-msg')
@@ -109,23 +109,23 @@
contents = re.sub('^[\r\n]*', '', contents)
if page.exists():
- if self.getOption('nocontent') != u'':
+ if self.options['nocontent'] != u'':
pagecontents = page.get()
- if pagecontents.find(self.getOption('nocontent')) != -1 or \
- pagecontents.find(self.getOption('nocontent').lower()) != -1:
- pywikibot.output(u'Page has %s so it is skipped' %
self.getOption('nocontent'))
+ if pagecontents.find(self.options['nocontent']) != -1 or \
+ pagecontents.find(self.options['nocontent'].lower()) != -1:
+ pywikibot.output(u'Page has %s so it is skipped' %
self.options['nocontent'])
return
- if self.getOption('append') == 'top':
+ if self.options['append'] == 'top':
pywikibot.output(u"Page %s already exists, appending on top!"
% title)
contents = contents + page.get()
comment = comment_top
- elif self.getOption('append') == 'bottom':
+ elif self.options['append'] == 'bottom':
pywikibot.output(u"Page %s already exists, appending on
bottom!"
% title)
contents = page.get() + contents
comment = comment_bottom
- elif self.getOption('force'):
+ elif self.options['force']:
pywikibot.output(u"Page %s already exists, ***overwriting!"
% title)
comment = comment_force
@@ -133,12 +133,12 @@
pywikibot.output(u"Page %s already exists, not adding!" %
title)
return
else:
- if self.getOption('autosummary'):
+ if self.options['autosummary']:
comment = ''
config.default_edit_summary = ''
try:
page.text = contents
- page.save(comment, minor=self.getOption('minor'))
+ page.save(comment, minor=self.options['minor'])
except pywikibot.LockedPage:
pywikibot.output(u"Page %s is locked; skipping." % title)
except pywikibot.EditConflict:
diff --git a/scripts/reflinks.py b/scripts/reflinks.py
index f1fb419..b2cbff6 100644
--- a/scripts/reflinks.py
+++ b/scripts/reflinks.py
@@ -409,10 +409,10 @@
break
if code:
manual += '/%s' % code
- if self.getOption('summary') is None:
+ if self.options['summary'] is None:
self.msg = i18n.twtranslate(self.site, 'reflinks-msg', locals())
else:
- self.msg = self.getOption('summary')
+ self.msg = self.options['summary']
self.stopPage = pywikibot.Page(self.site,
i18n.translate(self.site, stopPage))
@@ -535,7 +535,7 @@
contentType = headers.getheader('Content-Type')
if contentType and not self.MIME.search(contentType):
if ref.link.lower().endswith('.pdf') and \
- not self.getOption('ignorepdf'):
+ not self.options['ignorepdf']:
# If file has a PDF suffix
self.getPDFTitle(ref, f)
else:
@@ -751,8 +751,8 @@
else:
editedpages += 1
- if self.getOption('limit') and editedpages >=
self.getOption('limit'):
- pywikibot.output('Edited %s pages, stopping.' %
self.getOption('limit'))
+ if self.options['limit'] and editedpages >= self.options['limit']:
+ pywikibot.output('Edited %s pages, stopping.' %
self.options['limit'])
return
if editedpages % 20 == 0:
diff --git a/scripts/selflink.py b/scripts/selflink.py
index f618aaa..f408bf1 100644
--- a/scripts/selflink.py
+++ b/scripts/selflink.py
@@ -88,7 +88,7 @@
# at the beginning of the link, start red color.
# at the end of the link, reset the color to default
- if self.getOption('always'):
+ if self.options['always']:
choice = 'a'
else:
pre = page.text[max(0, match.start() - context):match.start()]
diff --git a/scripts/template.py b/scripts/template.py
index c605d29..083158c 100755
--- a/scripts/template.py
+++ b/scripts/template.py
@@ -214,19 +214,19 @@
self.generator = generator
self.templates = templates
site = pywikibot.Site()
- if self.getOption('addedCat'):
- self.options['addedCat'] = pywikibot.Category(site,
self.getOption('addedCat'))
+ if self.options['addedCat']:
+ self.options['addedCat'] = pywikibot.Category(site,
self.options['addedCat'])
comma = site.mediawiki_message('comma-separator')
# get edit summary message if it's empty
- if not self.getOption('summary'):
+ if not self.options['summary']:
params = {'list': comma.join(self.templates.keys()),
'num': len(self.templates)}
- if self.getOption('remove'):
+ if self.options['remove']:
self.options['summary'] = i18n.twntranslate(
site, 'template-removing', params)
- elif self.getOption('subst'):
+ elif self.options['subst']:
self.options['summary'] = i18n.twntranslate(
site, 'template-substituting', params)
else:
@@ -259,15 +259,15 @@
r'(?P<parameters>\s*\|.+?|) *}}',
re.DOTALL)
- if self.getOption('subst') and self.getOption('remove'):
+ if self.options['subst'] and self.options['remove']:
replacements.append((templateRegex,
'{{subst:%s\g<parameters>}}' % new))
exceptions['inside-tags'] = ['ref', 'gallery']
- elif self.getOption('subst'):
+ elif self.options['subst']:
replacements.append((templateRegex,
'{{subst:%s\g<parameters>}}' % old))
exceptions['inside-tags'] = ['ref', 'gallery']
- elif self.getOption('remove'):
+ elif self.options['remove']:
replacements.append((templateRegex, ''))
else:
template = pywikibot.Page(site, new, ns=10)
@@ -282,9 +282,9 @@
'{{%s\g<parameters>}}' % new))
replaceBot = replace.ReplaceRobot(self.generator, replacements,
- exceptions,
acceptall=self.getOption('always'),
- addedCat=self.getOption('addedCat'),
- summary=self.getOption('summary'))
+ exceptions,
acceptall=self.options['always'],
+ addedCat=self.options['addedCat'],
+ summary=self.options['summary'])
replaceBot.run()
diff --git a/scripts/touch.py b/scripts/touch.py
index 7c22a86..d385fcd 100755
--- a/scripts/touch.py
+++ b/scripts/touch.py
@@ -42,7 +42,7 @@
def run(self):
for page in self.generator:
- if self.getOption('purge'):
+ if self.options['purge']:
pywikibot.output(u'Page %s%s purged'
% (page.title(asLink=True),
"" if page.purge() else " not"))
@@ -51,7 +51,7 @@
# get the page, and save it using the unmodified text.
# whether or not getting a redirect throws an exception
# depends on the variable self.touch_redirects.
- page.get(get_redirect=self.getOption('redir'))
+ page.get(get_redirect=self.options['redir'])
page.save("Pywikibot touch script")
except pywikibot.NoPage:
pywikibot.error(u"Page %s does not exist."
diff --git a/scripts/unlink.py b/scripts/unlink.py
index b6b5d09..1cd642d 100755
--- a/scripts/unlink.py
+++ b/scripts/unlink.py
@@ -48,8 +48,8 @@
linktrail = self.pageToUnlink.site.linktrail()
gen = pagegenerators.ReferringPageGenerator(pageToUnlink)
- if self.getOption('namespaces') != []:
- gen = pagegenerators.NamespaceFilterPageGenerator(gen,
self.getOption('namespaces'))
+ if self.options['namespaces'] != []:
+ gen = pagegenerators.NamespaceFilterPageGenerator(gen,
self.options['namespaces'])
self.generator = pagegenerators.PreloadingGenerator(gen)
# The regular expression which finds links. Results consist of four
# groups:
@@ -96,7 +96,7 @@
else:
# at the beginning of the link, start red color.
# at the end of the link, reset the color to default
- if self.getOption('always'):
+ if self.options['always']:
choice = 'a'
else:
pywikibot.output(
--
To view, visit https://gerrit.wikimedia.org/r/152841
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: newchange
Gerrit-Change-Id: Ia26b64bcab49a89dd907de6ba5cabb4d8ed3bb76
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Ricordisamoa <[email protected]>
_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits