Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_log(self):
pywikibot.log('log')
self.assertEqual(newstdout.getvalue(), '')
self.assertEqual(newstderr.getvalue(), '')
module_name = 'no_module'
global_help = _GLOBAL_HELP % module_name
try:
module = import_module('%s' % module_name)
help_text = module.__doc__
if PY2 and isinstance(help_text, bytes):
help_text = help_text.decode('utf-8')
if hasattr(module, 'docuReplacements'):
for key, value in module.docuReplacements.items():
help_text = help_text.replace(key, value.strip('\n\r'))
pywikibot.stdout(help_text) # output to STDOUT
except Exception:
if module_name:
pywikibot.stdout('Sorry, no help available for %s' % module_name)
pywikibot.log('showHelp:', exc_info=True)
pywikibot.stdout(global_help)
def checkCommonscatLink(self, name=''):
"""Return the name of a valid commons category.
If the page is a redirect this function tries to follow it.
If the page doesn't exists the function will return an empty string
"""
pywikibot.log('getCommonscat: ' + name)
try:
commonsSite = self.site.image_repository()
# This can throw a pywikibot.BadTitle
commonsPage = pywikibot.Page(commonsSite, 'Category:' + name)
if not commonsPage.exists():
pywikibot.output('Commons category does not exist. '
'Examining deletion log...')
logpages = commonsSite.logevents(logtype='delete',
page=commonsPage)
for logitem in logpages:
loguser = logitem.user()
logcomment = logitem.comment()
# Some logic to extract the target page.
regex = (
r'moved to \[\[\:?Category:'
def getOpenStreetMapCats(latitude, longitude):
"""Get a list of location categories based on the OSM nomatim tool."""
result = []
location_list = getOpenStreetMap(latitude, longitude)
for i, location in enumerate(location_list):
pywikibot.log('Working on {!r}'.format(location))
if i <= len(location_list) - 3:
category = getCategoryByName(name=location,
parent=location_list[i + 1],
grandparent=location_list[i + 2])
elif i == len(location_list) - 2:
category = getCategoryByName(name=location,
parent=location_list[i + 1])
else:
category = getCategoryByName(name=location_list[i])
if category and not category == '':
result.append(category)
return result
command = ['+%i' % (line + 1)] # seems not to support columns
elif config.editor.startswith('jedit'):
command = ['+line:%i' % (line + 1)] # seems not to support columns
elif config.editor.startswith('vim'):
command = ['+%i' % (line + 1)] # seems not to support columns
elif config.editor.startswith('nano'):
command = ['+%i,%i' % (line + 1, column + 1)]
# Windows editors
elif config.editor.lower().endswith('notepad++.exe'):
command = ['-n%i' % (line + 1)] # seems not to support columns
else:
command = []
# See T102465 for problems relating to using config.editor unparsed.
command = [config.editor] + command + [file_name]
pywikibot.log(u'Running editor: %s' % TextEditor._concat(command))
return command
import scripts.isbn as scripts_isbn
except ImportError:
raise NotImplementedError(
'ISBN functionality not available. Install stdnum package.')
warn('package stdnum.isbn not found; using scripts.isbn',
ImportWarning)
isbn = match.group('code')
if stdnum_isbn:
try:
stdnum_isbn.validate(isbn)
except stdnum_isbn.ValidationError as e:
if strict:
raise
pywikibot.log('ISBN "%s" validation error: %s' % (isbn, e))
return isbn
return stdnum_isbn.format(isbn)
else:
try:
scripts_isbn.is_valid(isbn)
except scripts_isbn.InvalidIsbnException as e:
if strict:
raise
pywikibot.log('ISBN "%s" validation error: %s' % (isbn, e))
return isbn
isbn = scripts_isbn.getIsbn(isbn)
try:
isbn.format()
except scripts_isbn.InvalidIsbnException as e:
def loadpageinfo(self, page):
"""Load page info from api and save in page attributes"""
title = page.title(withSection=False)
query = self._generator(api.PropertyGenerator,
type_arg="info",
titles=title.encode(self.encoding()),
inprop="protection")
for pageitem in query:
if pageitem['title'] != title:
if pageitem['title'] in query.normalized \
and query.normalized[pageitem['title']] == title:
# page title was normalized by api
# this should never happen because the Link() constructor
# normalizes the title
pywikibot.log(
u"loadpageinfo: Page title '%s' was normalized to '%s'"
% (title, pageitem['title']))
else:
pywikibot.warning(
u"loadpageinfo: Query on %s returned data on '%s'"
% (page, pageitem['title']))
continue
api.update_page(page, pageitem)
try:
foundlink = pywikibot.Link(m.group('title'),
disambPage.site)
foundlink.parse()
except pywikibot.Error:
continue
# ignore interwiki links
if foundlink.site != disambPage.site:
continue
# Check whether the link found is to disambPage.
try:
if foundlink.canonical_title() != disambPage.title():
continue
except pywikibot.Error:
# must be a broken link
pywikibot.log(u"Invalid link [[%s]] in page [[%s]]"
% (m.group('title'), refPage.title()))
continue
n += 1
# how many bytes should be displayed around the current link
context = 60
# check if there's a dn-template here already
if (self.dnSkip and self.dn_template_str and
self.dn_template_str[:-2] in text[
m.end():m.end() + len(self.dn_template_str) + 8]):
continue
edit = EditOption('edit page', 'e', text, m.start(),
disambPage.title())
context_option = HighlightContextOption(
'more context', 'm', text, 60, start=m.start(),
end=m.end())
raise EditConflict(self._ep_errors[err.code] % errdata)
if err.code in ("protectedpage", "cascadeprotected"):
raise LockedPage(errdata['title'])
if err.code in self._ep_errors:
raise Error(self._ep_errors[err.code] % errdata)
pywikibot.debug(
u"editpage: Unexpected error code '%s' received."
% err.code,
_logger)
raise
assert ("edit" in result and "result" in result["edit"]), result
if result["edit"]["result"] == "Success":
self.unlock_page(page)
if "nochange" in result["edit"]:
# null edit, page not changed
pywikibot.log(u"Page [[%s]] saved without any changes."
% page.title())
return True
page._revid = result["edit"]["newrevid"]
# see http://www.mediawiki.org/wiki/API:Wikimania_2006_API_discussion#Notes
# not safe to assume that saved text is the same as sent
self.loadrevisions(page, getText=True)
return True
elif result["edit"]["result"] == "Failure":
if "captcha" in result["edit"]:
captcha = result["edit"]["captcha"]
req['captchaid'] = captcha['id']
if captcha["type"] == "math":
req['captchaword'] = input(captcha["question"])
continue
elif "url" in captcha:
webbrowser.open(url)