jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/783662 )
Change subject: [IMPR] Deprecate tools.formatter.color_format ......................................................................
[IMPR] Deprecate tools.formatter.color_format
Also replace all its usage with the new color format style and update tests accordingly
Change-Id: I7ecda3dd87aee11d2543a9faa50f492fd84869bd --- M pywikibot/__init__.py M pywikibot/bot.py M pywikibot/bot_choice.py M pywikibot/data/api.py M pywikibot/diff.py M pywikibot/logging.py M pywikibot/specialbots/_upload.py M pywikibot/tools/formatter.py M scripts/category.py M scripts/change_pagelang.py M scripts/commons_information.py M scripts/fixing_redirects.py M scripts/imagetransfer.py M scripts/interwiki.py M scripts/maintenance/colors.py M scripts/misspelling.py M scripts/nowcommons.py M scripts/reflinks.py M scripts/revertbot.py M scripts/speedy_delete.py M scripts/weblinkchecker.py M scripts/welcome.py M tests/diff_tests.py M tests/tools_formatter_tests.py 24 files changed, 174 insertions(+), 208 deletions(-)
Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py index 348cfa7..d9ed711 100644 --- a/pywikibot/__init__.py +++ b/pywikibot/__init__.py @@ -67,7 +67,6 @@ ) from pywikibot.site import APISite, BaseSite, DataSite from pywikibot.tools import classproperty, normalize_username -from pywikibot.tools.formatter import color_format
ItemPageStrNoneType = Union[str, 'ItemPage', None] @@ -1303,9 +1302,9 @@
num, sec = remaining() if num > 0 and sec.total_seconds() > _config.noisysleep: - output(color_format( - '{lightblue}Waiting for {num} pages to be put. ' - 'Estimated time remaining: {sec}{default}', num=num, sec=sec)) + output('<<lightblue>>Waiting for {num} pages to be put. ' + 'Estimated time remaining: {sec}<<default>>' + .format(num=num, sec=sec))
if _putthread is not threading.current_thread(): while (_putthread.is_alive() diff --git a/pywikibot/bot.py b/pywikibot/bot.py index 360b8c3..7401883 100644 --- a/pywikibot/bot.py +++ b/pywikibot/bot.py @@ -179,7 +179,6 @@ strtobool, ) from pywikibot.tools._logging import LoggingFormatter -from pywikibot.tools.formatter import color_format
if TYPE_CHECKING: @@ -777,28 +776,29 @@ if isinstance(c, AlwaysChoice) and c.handle_link(): return c.answer
+ question = 'Should the link ' if self.context > 0: rng = self.current_range text = self.current_text # at the beginning of the link, start red color. # at the end of the link, reset the color to default pywikibot.output(text[max(0, rng[0] - self.context): rng[0]] - + color_format('{lightred}{0}{default}', - text[rng[0]: rng[1]]) + + '<<lightred>>{}<<default>>'.format( + text[rng[0]: rng[1]]) + text[rng[1]: rng[1] + self.context]) - question = 'Should the link ' else: - question = 'Should the link {lightred}{0}{default} ' + question += '<<lightred>>{}<<default>> '.format( + self._old.canonical_title())
if self._new is False: question += 'be unlinked?' else: - question += color_format('target to {lightpurple}{0}{default}?', - self._new.canonical_title()) + question += 'target to <<lightpurple>>{}<<default>>?'.format( + self._new.canonical_title())
- choice = pywikibot.input_choice( - color_format(question, self._old.canonical_title()), - choices, default=self._default, automatic_quit=self._quit) + choice = pywikibot.input_choice(question, choices, + default=self._default, + automatic_quit=self._quit)
assert isinstance(choice, str) return self.handle_answer(choice) @@ -1312,8 +1312,8 @@ msg = 'Working on {!r}'.format(page.title()) if config.colorized_output: log(msg) - stdout(color_format('\n\n>>> {lightpurple}{0}{default} <<<', - page.title())) + stdout('\n\n>>> <<lightpurple>>{}<<default>> <<<' + .format(page.title())) else: stdout(msg)
diff --git a/pywikibot/bot_choice.py b/pywikibot/bot_choice.py index 309fb94..c59ba79 100644 --- a/pywikibot/bot_choice.py +++ b/pywikibot/bot_choice.py @@ -588,12 +588,11 @@ """Highlighted output section of the text.""" start = max(0, self.start - self.context) end = min(len(self.text), self.end + self.context) - color_format = pywikibot.tools.formatter.color_format - return color_format('{}{%(color)s}{}{default}{}' - % {'color': self.color}, - self.text[start:self.start], - self.text[self.start:self.end], - self.text[self.end:end]) + return '{}<<{color}>>{}<<default>>{}'.format( + self.text[start:self.start], + self.text[self.start:self.end], + self.text[self.end:end], + color=self.color)
@deprecated('pywikibot.output(HighlightContextOption.out)', since='6.2.0') diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py index 9dfdb90..cc1183b 100644 --- a/pywikibot/data/api.py +++ b/pywikibot/data/api.py @@ -42,7 +42,6 @@ from pywikibot.login import LoginStatus from pywikibot.textlib import removeHTMLParts from pywikibot.tools import PYTHON_VERSION, itergroup -from pywikibot.tools.formatter import color_format
_logger = 'data.api' @@ -1339,9 +1338,8 @@ """Simulate action.""" if action and config.simulate and ( self.write or action in config.actions_to_block): - pywikibot.output(color_format( - '{black;yellow}SIMULATION: {} action blocked.{default}', - action)) + pywikibot.output('<<black;yellow>>SIMULATION: {} action blocked.' + '<<default>>'.format(action)) # for more realistic simulation if config.simulate is not True: pywikibot.sleep(float(config.simulate)) diff --git a/pywikibot/diff.py b/pywikibot/diff.py index 45c9246..91d99b4 100644 --- a/pywikibot/diff.py +++ b/pywikibot/diff.py @@ -16,7 +16,6 @@ import pywikibot from pywikibot.backports import Dict, Iterable, List, Sequence, Tuple from pywikibot.tools import chars -from pywikibot.tools.formatter import color_format
class Hunk: @@ -167,8 +166,8 @@
if line_ref is None: if color in self.colors: - colored_line = color_format('{color}{0}{default}', - line, color=self.colors[color]) + colored_line = '<<{color}>>{}<<default>>'.format( + line, color=self.colors[color]) return colored_line return line
@@ -184,17 +183,17 @@ apply_color = self.colors[color] else: apply_color = 'default;' + self.bg_colors[color] - char_tagged = color_format('{color}{0}', - char, color=apply_color) + char_tagged = '<<{color}>>{}'.format(char, + color=apply_color) color_closed = False else: if char_ref == ' ': - char_tagged = color_format('{default}{0}', char) + char_tagged = '<<default>>{}'.format(char) color_closed = True colored_line += char_tagged
if not color_closed: - colored_line += color_format('{default}') + colored_line += '<<default>>'
return colored_line
@@ -374,10 +373,9 @@
context_range = self._get_context_range(hunks)
- output = color_format('{aqua}{0}{default}\n{1}', - Hunk.get_header_text(*context_range), - extend_context(context_range[0][0], - hunks[0].a_rng[0])) + output = '<<aqua>>{}<<default>>\n{}'.format( + Hunk.get_header_text(*context_range), + extend_context(context_range[0][0], hunks[0].a_rng[0])) previous_hunk = None for hunk in hunks: if previous_hunk: @@ -528,8 +526,8 @@ pywikibot.output( 'Split into {} hunks'.format(len(super_hunk._hunks))) else: # choice == '?': - pywikibot.output(color_format( - '{purple}{0}{default}', '\n'.join( + pywikibot.output( + '<<purple>>{}<<default>>'.format('\n'.join( '{} -> {}'.format(answer, help_msg[answer]) for answer in answers)))
@@ -568,24 +566,24 @@ by_letter: if text_a and text_b are single lines, comparison can be done
""" - template = '{2}{lightpurple}{0:{1}^50}{default}{2}' + template = '{2}<<lightpurple>>{0:{1}^50}<<default>>{2}'
patch = PatchManager(oldtext, newtext, context=n, by_letter=by_letter) - pywikibot.output(color_format(template, ' ALL CHANGES ', '*', '\n')) + pywikibot.output(template.format(' ALL CHANGES ', '*', '\n'))
for hunk in patch.hunks: pywikibot.output(hunk.diff_text) - pywikibot.output(color_format(template, ' REVIEW CHANGES ', '*', '\n')) + pywikibot.output(template.format(' REVIEW CHANGES ', '*', '\n'))
text_list = patch.apply() - pywikibot.output(color_format(template, ' APPROVED CHANGES ', '*', '\n')) + pywikibot.output(template.format(' APPROVED CHANGES ', '*', '\n'))
if any(hunk.reviewed == hunk.APPR for hunk in patch.hunks): for hunk in patch.hunks: if hunk.reviewed == hunk.APPR: pywikibot.output(hunk.diff_text) else: - pywikibot.output(color_format(template, 'None.', '', '')) + pywikibot.output(template.format('None.', '', ''))
text = ''.join(text_list)
diff --git a/pywikibot/logging.py b/pywikibot/logging.py index 4bbc2ca..30cdc0b 100644 --- a/pywikibot/logging.py +++ b/pywikibot/logging.py @@ -108,7 +108,7 @@
def output(text: object, decoder: Optional[str] = None, newline: bool = True, **kwargs: Any) -> None: - r"""Output a message to the user via the userinterface. + """Output a message to the user via the userinterface.
Works like print, but uses the encoding used by the user's console (console_encoding in the configuration file) instead of ASCII. @@ -119,10 +119,8 @@ If newline is True, a line feed will be added after printing the text.
text can contain special sequences to create colored output. These - consist of the escape character \03 and the color name in curly braces, - e. g. \03{lightpurple}. \03{default} resets the color. By using the - color_format method from pywikibot.tools.formatter, the escape character - may be omitted. + consist of the color name in angle bracket, e. g. <<lightpurple>>. + <<default>> resets the color.
Other keyword arguments are passed unchanged to the logger; so far, the only argument that is useful is "exc_info=True", which causes the diff --git a/pywikibot/specialbots/_upload.py b/pywikibot/specialbots/_upload.py index 4bfb79f..650c730 100644 --- a/pywikibot/specialbots/_upload.py +++ b/pywikibot/specialbots/_upload.py @@ -23,7 +23,6 @@ from pywikibot.backports import List from pywikibot.bot import BaseBot, QuitKeyboardInterrupt from pywikibot.exceptions import APIError, FatalServerError, NoPageError -from pywikibot.tools.formatter import color_format
class UploadRobot(BaseBot): @@ -328,9 +327,8 @@
while not self.description or self.verify_description: if not self.description: - pywikibot.output(color_format( - '{lightred}It is not possible to upload a file ' - 'without a description.{default}')) + pywikibot.output('<<lightred>>It is not possible to upload a ' + 'file without a description.<<default>>') assert not self.opt.always # if no description, ask if user want to add one or quit, # and loop until one is filled. diff --git a/pywikibot/tools/formatter.py b/pywikibot/tools/formatter.py index 87dcbd1..6a4bf2f 100644 --- a/pywikibot/tools/formatter.py +++ b/pywikibot/tools/formatter.py @@ -123,6 +123,8 @@ return super().vformat(format_string, args, kwargs)
+@deprecated('New color format pattern like <<color>>colored text<<default>>', + since='7.2.0') def color_format(text: str, *args, **kwargs) -> str: r""" Do ``str.format`` without having to worry about colors. @@ -134,6 +136,10 @@ You may use a variant {color} by assigning a valid color to a named parameter color.
+ .. deprecated:: 7.2 + new color format pattern like <<color>>colored text<<default>> + may be used instead. + :param text: The format template string :return: The formatted string """ diff --git a/scripts/category.py b/scripts/category.py index f86bc79..0119536 100755 --- a/scripts/category.py +++ b/scripts/category.py @@ -153,7 +153,6 @@ PageSaveRelatedError, ) from pywikibot.tools import open_archive -from pywikibot.tools.formatter import color_format
# This is required for the text that is shown when you run this script @@ -1062,8 +1061,7 @@ if cat != original_cat: text += cat.title(as_link=True) else: - text += color_format( - '{lightpurple}{0}{default}', + text += '<<lightpurple>>{}<<default>>'.format( current_cat.title(as_link=True)) text += '\n' return text @@ -1117,8 +1115,8 @@
# show the title of the page where the link was found. pywikibot.output('') - pywikibot.output(color_format( - '>>> {lightpurple}{0}{default} <<<', member.title())) + pywikibot.output('>>> <<lightpurple>>{}<<default>> <<<' + .format(member.title()))
# determine a reasonable amount of context. try: @@ -1176,17 +1174,16 @@ pywikibot.output('') options = (supercat_option, subcat_option, - StandardOption(color_format( - 'save page to category {lightpurple}{0}{default}', - current_cat.title(with_ns=False)), 'c'), + StandardOption( + 'save page to category <<lightpurple>>{}<<default>>' + .format(current_cat.title(with_ns=False)), 'c'), StandardOption('remove the category from page', 'r'), StandardOption('skip page', 's'), context_option, - StandardOption('jump to custom category', 'j'), - ) - choice = pywikibot.input_choice(color_format( - 'Choice for page {lightpurple}{0}{default}:', member.title()), - options, default='c') + StandardOption('jump to custom category', 'j')) + choice = pywikibot.input_choice( + 'Choice for page <<lightpurple>>{}<<default>>:' + .format(member.title()), options, default='c')
if choice == 'c': pywikibot.output('Saving page to {}'.format(current_cat.title())) @@ -1414,13 +1411,11 @@ pywikibot.output('\t{}'.format(grandchild.title()))
for grandchild in overcategorized: - msg = color_format( - 'Remove "{lightpurple}{}{default}" from "{}" ' - 'because it is already under ' - 'subcategory "{green}{}{default}"?', - grandchild.title(with_ns=False), - self.cat.title(with_ns=False), - child.title(with_ns=False)) + msg = ('Remove "<<lightpurple>>{}<<default>>" from "{}" because ' + 'it is already under subcategory "<<green>>{}<<default>>"?' + .format(grandchild.title(with_ns=False), + self.cat.title(with_ns=False), + child.title(with_ns=False)))
if not self.user_confirm(msg): continue diff --git a/scripts/change_pagelang.py b/scripts/change_pagelang.py index 5103d93..a8aec48 100755 --- a/scripts/change_pagelang.py +++ b/scripts/change_pagelang.py @@ -28,7 +28,6 @@ import pywikibot from pywikibot import pagegenerators from pywikibot.bot import ConfigParserBot, SingleSiteBot -from pywikibot.tools.formatter import color_format
docuReplacements = { # noqa: N816 @@ -68,10 +67,9 @@ 'token': token} r = self.site.simple_request(**parameters) r.submit() - pywikibot.output(color_format( - '{lightpurple}{0}{default}: Setting ' - 'page language to {green}{1}{default}', - page.title(as_link=True), self.opt.setlang)) + pywikibot.output('<<lightpurple>>{}<<default>>: Setting ' + 'page language to <<green>>{}<<default>>' + .format(page.title(as_link=True), self.opt.setlang))
def treat(self, page) -> None: """Treat a page. @@ -93,25 +91,25 @@ sitelang = langcheck['general']['lang']
if self.opt.setlang == currentlang: - pywikibot.output(color_format( - '{lightpurple}{0}{default}: This page is already set to ' - '{green}{1}{default}; skipping.', - page.title(as_link=True), self.opt.setlang)) + pywikibot.output('<<lightpurple>>{}<<default>>: This page is ' + 'already set to <<green>>{}<<default>>; skipping.' + .format(page.title(as_link=True), + self.opt.setlang)) elif currentlang == sitelang or self.opt.always: self.changelang(page) elif self.opt.never: - pywikibot.output(color_format( - '{lightpurple}{0}{default}: This page already has a ' - 'different content language {yellow}{1}{default} set; ' - 'skipping.', page.title(as_link=True), currentlang)) + pywikibot.output( + '<<lightpurple>>{}<<default>>: This page already has a ' + 'different content language <<yellow>>{}<<default>> set; ' + 'skipping.'.format(page.title(as_link=True), currentlang)) else: - pywikibot.output(color_format( - '\n\n>>> {lightpurple}{0}{default} <<<', page.title())) - choice = pywikibot.input_choice(color_format( + pywikibot.output('\n\n>>> <<lightpurple>>{}<<default>> <<<' + .format(page.title())) + choice = pywikibot.input_choice( 'The content language for this page is already set to ' - '{yellow}{0}{default}, which is different from the ' - 'default ({1}). Change it to {green}{2}{default} anyway?', - currentlang, sitelang, self.opt.setlang), + '<<yellow>>{}<<default>>, which is different from the ' + 'default ({}). Change it to <<green>>{}<<default>> anyway?' + .format(currentlang, sitelang, self.opt.setlang), [('Always', 'a'), ('Yes', 'y'), ('No', 'n'), ('Never', 'v')], default='Y') if choice == 'a': diff --git a/scripts/commons_information.py b/scripts/commons_information.py index 466ddfe..a17f134 100755 --- a/scripts/commons_information.py +++ b/scripts/commons_information.py @@ -10,7 +10,6 @@ import pywikibot from pywikibot import i18n, pagegenerators from pywikibot.bot import ExistingPageBot, SingleSiteBot -from pywikibot.tools.formatter import color_format
try: @@ -132,12 +131,12 @@ pywikibot.output(value) langs = self.detect_langs(value) if langs: - pywikibot.output(color_format( - '{lightblue}Hints from langdetect:{default}')) + pywikibot.output( + '<<lightblue>>Hints from langdetect:<<default>>') for language in langs: - pywikibot.output(color_format( - '{{lightblue}}{obj.lang}: {obj.prob}{{default}}', - obj=language)) + pywikibot.output( + '<<lightblue>>{obj.lang}: {obj.prob}<<default>>' + .format(obj=language)) lang = pywikibot.input( 'Enter the language of the displayed text:').strip() if lang != '': diff --git a/scripts/fixing_redirects.py b/scripts/fixing_redirects.py index 8707595..3814a1a 100755 --- a/scripts/fixing_redirects.py +++ b/scripts/fixing_redirects.py @@ -44,7 +44,6 @@ from pywikibot.textlib import does_text_contain_section, isDisabled from pywikibot.tools import first_lower from pywikibot.tools import first_upper as firstcap -from pywikibot.tools.formatter import color_format
# This is required for the text that is shown when you run this script @@ -240,9 +239,9 @@
mysite = pywikibot.Site() if mysite.sitename == 'wikipedia:nl': - pywikibot.output(color_format( - '{lightred}There is consensus on the Dutch Wikipedia that ' - 'bots should not be used to fix redirects.{default}')) + pywikibot.output( + '<<lightred>>There is consensus on the Dutch Wikipedia that ' + 'bots should not be used to fix redirects.<<default>>') return
if featured: diff --git a/scripts/imagetransfer.py b/scripts/imagetransfer.py index e8e08d9..4310e33 100755 --- a/scripts/imagetransfer.py +++ b/scripts/imagetransfer.py @@ -49,7 +49,6 @@ from pywikibot.bot import ExistingPageBot, SingleSiteBot from pywikibot.exceptions import IsRedirectPageError, NoPageError from pywikibot.specialbots import UploadRobot -from pywikibot.tools.formatter import color_format
docuReplacements = { @@ -323,8 +322,7 @@ # remove the selected image from the list imagelist.pop(todo) else: - pywikibot.output( - color_format('{yellow}No such image number.{default}')) + pywikibot.output('<<yellow>>No such image number.<<default>>')
def transfer_allowed(self, image) -> bool: """Check whether transfer is allowed.""" @@ -333,9 +331,8 @@ if not self.opt.force_if_shared \ and image.file_is_shared() \ and image.site.image_repository() == target_repo: - pywikibot.output(color_format( - '{yellow}The image is already shared on {}.{default}', - target_repo)) + pywikibot.output('<<yellow>>The image is already shared on {}.' + '<<default>>'.format(target_repo)) return False return True
diff --git a/scripts/interwiki.py b/scripts/interwiki.py index 8d6a194..bcd3721 100755 --- a/scripts/interwiki.py +++ b/scripts/interwiki.py @@ -366,7 +366,6 @@ UnknownSiteError, ) from pywikibot.tools import SizedKeyCollection, first_upper -from pywikibot.tools.formatter import color_format
docuReplacements = { @@ -1648,9 +1647,8 @@ self.conf.note('No changes needed on page {}'.format(page)) return False
- # Show a message in purple. - pywikibot.output(color_format( - '{lightpurple}Updating links on page {0}.{default}', page)) + pywikibot.output('<<lightpurple>>Updating links on page {}.<<default>>' + .format(page)) pywikibot.output('Changes to be made: {}'.format(mods)) oldtext = page.get() template = (page.namespace() == 10) diff --git a/scripts/maintenance/colors.py b/scripts/maintenance/colors.py index 4bd6fcf..9a0434d 100755 --- a/scripts/maintenance/colors.py +++ b/scripts/maintenance/colors.py @@ -1,13 +1,12 @@ #!/usr/bin/python3 """Utility to show pywikibot colors.""" # -# (C) Pywikibot team, 2016-2020 +# (C) Pywikibot team, 2016-2022 # # Distributed under the terms of the MIT license. # import pywikibot from pywikibot.tools import itergroup -from pywikibot.tools.formatter import color_format from pywikibot.userinterfaces.terminal_interface_base import colors
@@ -31,9 +30,9 @@ line = '' for fg_col in fg_col_group: line += ' ' - line += color_format('{color}{0}{default}', - fg_col.ljust(max_len_fg_colors), - color='{};{}'.format(fg_col, bg_col)) + line += '<<{color}>>{}<<default>>'.format( + fg_col.ljust(max_len_fg_colors), + color='{};{}'.format(fg_col, bg_col))
line = '{} {}'.format(bg_col.ljust(max_len_bc_color), line) pywikibot.output(line) diff --git a/scripts/misspelling.py b/scripts/misspelling.py index 34f615f..a7afa30 100755 --- a/scripts/misspelling.py +++ b/scripts/misspelling.py @@ -30,7 +30,6 @@
import pywikibot from pywikibot import i18n, pagegenerators -from pywikibot.tools.formatter import color_format from scripts.solve_disambiguation import DisambiguationRobot as BaseDisambigBot
@@ -65,8 +64,7 @@ if cat is not None]
if templates: - pywikibot.output(color_format( - '{yellow}Working on templates...{default}')) + pywikibot.output('<<yellow>>Working on templates...<<default>>') if isinstance(templates, str): templates = (templates, )
@@ -82,8 +80,7 @@ '-start parameter is not supported on this wiki\n' 'because templates are used for misspellings.') elif categories: - pywikibot.output(color_format( - '{yellow}Working on categories...{default}')) + pywikibot.output('<<yellow>>Working on categories...<<default>>') generators = ( pagegenerators.CategorizedPageGenerator( cat, recurse=True, start=self.opt.start diff --git a/scripts/nowcommons.py b/scripts/nowcommons.py index 9ec0557..d323443 100755 --- a/scripts/nowcommons.py +++ b/scripts/nowcommons.py @@ -56,7 +56,6 @@ from pywikibot.bot import Bot, ConfigParserBot from pywikibot.exceptions import IsRedirectPageError, NoPageError from pywikibot.tools import filter_unique -from pywikibot.tools.formatter import color_format from scripts.image import ImageRobot as ImageBot
@@ -280,17 +279,17 @@ != commons_file_page.title(with_ns=False)): using_pages = list(local_file_page.using_pages()) if using_pages and using_pages != [local_file_page]: - pywikibot.output(color_format( - '"{lightred}{0}{default}" ' - 'is still used in {1} pages.', - local_file_page.title(with_ns=False), - len(using_pages))) - if self.opt.replace: - pywikibot.output(color_format( - 'Replacing "{lightred}{0}{default}" by ' - '"{lightgreen}{1}{default}".', + pywikibot.output( + '"<<lightred>>{}<<default>>" is still used in {} ' + 'pages.'.format( local_file_page.title(with_ns=False), - commons_file_page.title(with_ns=False))) + len(using_pages))) + if self.opt.replace: + pywikibot.output( + 'Replacing "<<lightred>>{}<<default>>" by ' + '"<<lightgreen>>{}<<default>>".'.format( + local_file_page.title(with_ns=False), + commons_file_page.title(with_ns=False))) bot = ImageBot( local_file_page.usingPages(), local_file_page.title(with_ns=False), @@ -319,10 +318,10 @@ else: pywikibot.output('Please change them manually.') continue - pywikibot.output(color_format( - 'No page is using "{lightgreen}{0}{default}" ' - 'anymore.', - local_file_page.title(with_ns=False))) + pywikibot.output( + 'No page is using "<<lightgreen>>{}<<default>>" ' + 'anymore.'.format( + local_file_page.title(with_ns=False))) commons_text = commons_file_page.get() if not self.opt.replaceonly: if sha1 == commons_file_page.latest_file_info.sha1: @@ -335,13 +334,14 @@ 'the old versions are not worth keeping.') continue if self.opt.always is False: - format_str = color_format( - '\n\n>>>> Description on {lightpurple}%s' - '{default} <<<<\n') - pywikibot.output(format_str % page.title()) + format_str = ( + '\n\n>>>> Description on ' + '<<<lightpurple>>{}<<default>> <<<<\n' + ) + pywikibot.output(format_str.format(page.title())) pywikibot.output(local_file_page.get()) - pywikibot.output(format_str % - commons_file_page.title()) + pywikibot.output( + format_str.format(commons_file_page.title())) pywikibot.output(commons_text) if pywikibot.input_yn( 'Does the description on Commons contain ' diff --git a/scripts/reflinks.py b/scripts/reflinks.py index 3ce0467..06492d5 100755 --- a/scripts/reflinks.py +++ b/scripts/reflinks.py @@ -79,7 +79,6 @@ ) from pywikibot.textlib import replaceExcept from pywikibot.tools.chars import string2html -from pywikibot.tools.formatter import color_format from scripts import noreferences
@@ -598,9 +597,8 @@ # If file has a PDF suffix self.getPDFTitle(ref, r) else: - pywikibot.output(color_format( - '{lightyellow}WARNING{default} : media : {} ', - ref.link)) + pywikibot.output('<<lightyellow>>WARNING<<default>> : ' + 'media : {} '.format(ref.link))
if not ref.title: repl = ref.refLink() @@ -609,9 +607,9 @@ ref.transform(ispdf=True) repl = ref.refTitle() else: - pywikibot.output(color_format( - '{lightyellow}WARNING{default} : ' - 'PDF title blacklisted : {0} ', ref.title)) + pywikibot.output('<<lightyellow>>WARNING<<default>> : ' + 'PDF title blacklisted : {} ' + .format(ref.title)) repl = ref.refLink()
new_text = new_text.replace(match.group(), repl) @@ -623,16 +621,16 @@ and domain.findall(redir) == domain.findall(link): if soft404.search(redir) \ and not soft404.search(ref.link): - pywikibot.output(color_format( - '{lightyellow}WARNING{default} : ' - 'Redirect 404 : {0} ', ref.link)) + pywikibot.output('<<lightyellow>>WARNING<<default>> : ' + 'Redirect 404 : {} ' + .format(ref.link)) continue
if dirIndex.match(redir) \ and not dirIndex.match(ref.link): - pywikibot.output(color_format( - '{lightyellow}WARNING{default} : ' - 'Redirect to root : {0} ', ref.link)) + pywikibot.output('<<lightyellow>>WARNING<<default>> : ' + 'Redirect to root : {} ' + .format(ref.link)) continue
if r.status_code != HTTPStatus.OK: @@ -652,9 +650,8 @@ # example: # http://www.adminet.com/jo/20010615%C2%A6/ECOC0100037D.html # in [[fr:Cyanure]] - pywikibot.output(color_format( - '{lightred}Bad link{default} : {0} in {1}', - ref.url, page.title(as_link=True))) + pywikibot.output('<<lightred>>Bad link<<default>> : {} in {}' + .format(ref.url, page.title(as_link=True))) continue
except (ValueError, # urllib3.LocationParseError derives from it @@ -704,9 +701,8 @@ continue
if not self.MIME.search(content_type): - pywikibot.output(color_format( - '{lightyellow}WARNING{default} : media : {0} ', - ref.link)) + pywikibot.output('<<lightyellow>>WARNING<<default>> : media : ' + '{} '.format(ref.link)) repl = ref.refLink() new_text = new_text.replace(match.group(), repl) continue @@ -729,9 +725,9 @@ if self.titleBlackList.match(ref.title): repl = ref.refLink() new_text = new_text.replace(match.group(), repl) - pywikibot.output(color_format( - '{lightred}WARNING{default} {0} : ' - 'Blacklisted title ({1})', ref.link, ref.title)) + pywikibot.output('<<lightred>>WARNING<<default>> {} : ' + 'Blacklisted title ({})' + .format(ref.link, ref.title)) continue
# Truncate long titles. 175 is arbitrary @@ -765,8 +761,8 @@ if self.site_stop_page and self.counter['write'] % 20 == 0: self.stop_page = pywikibot.Page(self.site, self.site_stop_page) if self.stop_page.exists(): - pywikibot.output(color_format( - '{lightgreen}Checking stop page...{default}')) + pywikibot.output( + '<<lightgreen>>Checking stop page...<<default>>') actual_rev = self.stop_page.latest_revision_id if actual_rev != self.stop_page_rev_id: pywikibot.output( diff --git a/scripts/revertbot.py b/scripts/revertbot.py index 0273267..551f81f 100755 --- a/scripts/revertbot.py +++ b/scripts/revertbot.py @@ -46,7 +46,6 @@ from pywikibot.bot import OptionHandler from pywikibot.date import format_date, formatYear from pywikibot.exceptions import APIError, Error -from pywikibot.tools.formatter import color_format
class BaseRevertBot(OptionHandler): @@ -111,9 +110,10 @@
rev = history[1]
- pywikibot.output(color_format( - '\n\n>>> {lightpurple}{0}{default} <<<', - page.title(as_link=True, force_interwiki=True, textlink=True))) + pywikibot.output('\n\n>>> <<lightpurple>>{0}<<default>> <<<' + .format(page.title(as_link=True, + force_interwiki=True, + textlink=True)))
if not self.opt.rollback: comment = i18n.twtranslate( diff --git a/scripts/speedy_delete.py b/scripts/speedy_delete.py index ed8f386..7271e84 100755 --- a/scripts/speedy_delete.py +++ b/scripts/speedy_delete.py @@ -32,7 +32,6 @@ from pywikibot import i18n, pagegenerators from pywikibot.bot import ExistingPageBot, SingleSiteBot from pywikibot.exceptions import Error -from pywikibot.tools.formatter import color_format
class SpeedyBot(SingleSiteBot, ExistingPageBot): @@ -374,9 +373,8 @@ def get_reason_for_deletion(self, page): """Get a reason for speedy deletion from operator.""" suggested_reason = self.guess_reason_for_deletion(page) - pywikibot.output(color_format( - 'The suggested reason is: {lightred}{}{default}', - suggested_reason)) + pywikibot.output('The suggested reason is: <<lightred>>{}<<default>>' + .format(suggested_reason))
# We don't use i18n.translate() here because for some languages the # entry is intentionally left out. @@ -430,7 +428,7 @@ """Process one page.""" page = self.current_page
- color_line = color_format('{blue}{}{default}', '_' * 80) + color_line = '<<blue>>{}<<default>>'.format('_' * 80) pywikibot.output(color_line) pywikibot.output(page.extract('wiki', lines=self.LINES)) pywikibot.output(color_line) @@ -453,9 +451,8 @@ # delete the current page elif choice == 'd': reason = self.get_reason_for_deletion(page) - pywikibot.output(color_format( - 'The chosen reason is: {lightred}{}{default}', - reason)) + pywikibot.output('The chosen reason is: <<lightred>>{}<<default>>' + .format(reason)) page.delete(reason, prompt=False)
# skip this page diff --git a/scripts/weblinkchecker.py b/scripts/weblinkchecker.py index 8f68746..4c49ee9 100755 --- a/scripts/weblinkchecker.py +++ b/scripts/weblinkchecker.py @@ -132,7 +132,6 @@ XMLDumpPageGenerator as _XMLDumpPageGenerator, ) from pywikibot.tools import ThreadList -from pywikibot.tools.formatter import color_format
try: @@ -511,16 +510,14 @@ url, error_report, containing_page, archive_url = self.queue[0] self.queue = self.queue[1:] talk_page = containing_page.toggleTalkPage() - pywikibot.output(color_format( - '{lightaqua}** Reporting dead link on {}...{default}', - talk_page)) + pywikibot.output('<<lightaqua>>** Reporting dead link on {}...' + '<<default>>'.format(talk_page)) try: content = talk_page.get() + '\n\n\n' if url in content: - pywikibot.output(color_format( - '{lightaqua}** Dead link seems to have ' - 'already been reported on {}{default}', - talk_page)) + pywikibot.output('<<lightaqua>>** Dead link seems to ' + 'have already been reported on {}' + '<<default>>'.format(talk_page)) continue except (NoPageError, IsRedirectPageError): content = '' @@ -557,10 +554,10 @@ try: talk_page.put(content, comment) except SpamblacklistError as error: - pywikibot.output(color_format( - '{lightaqua}** SpamblacklistError while trying to ' - 'change {0}: {1}{default}', - talk_page, error.url)) + pywikibot.output( + '<<lightaqua>>** SpamblacklistError while trying to ' + 'change {}: {}<<default>>' + .format(talk_page, error.url))
class WeblinkCheckerRobot(SingleSiteBot, ExistingPageBot): diff --git a/scripts/welcome.py b/scripts/welcome.py index cf290a8..223b327 100755 --- a/scripts/welcome.py +++ b/scripts/welcome.py @@ -176,7 +176,6 @@ from pywikibot.backports import Dict, Generator, List # skipcq: PY-W2000 from pywikibot.bot import SingleSiteBot from pywikibot.exceptions import EditConflictError, Error, HiddenKeyError -from pywikibot.tools.formatter import color_format
locale.setlocale(locale.LC_ALL, '') @@ -877,9 +876,8 @@ def show_status(message=Msg.DEFAULT) -> None: """Output colorized status.""" msg, color = message.value - pywikibot.output(color_format('{color}[{msg:5}]{default} ', - msg=msg, color=color), - newline=False) + pywikibot.output('<<{color}>>[{msg:5}]<<default>> ' + .format(msg=msg, color=color), newline=False)
def teardown(self) -> None: """Some cleanups after run operation.""" diff --git a/tests/diff_tests.py b/tests/diff_tests.py index adc51e8..6ce8ca0 100755 --- a/tests/diff_tests.py +++ b/tests/diff_tests.py @@ -201,17 +201,17 @@ newtext = 'new'
# output messages expected during testing - diff_message = ('\x03{lightred}- old\n\x03{default}\x03{lightgreen}+ ' - 'new\n\x03{default}') - none_message = '\x03{{lightpurple}}{0: ^50}\x03{{default}}'.format('None.') - header_base = '\n\x03{{lightpurple}}{0:*^50}\x03{{default}}\n' + diff_message = ('<<lightred>>- old\n<<default>><<lightgreen>>+ ' + 'new\n<<default>>') + none_message = '<<lightpurple>>{0: ^50}<<default>>'.format('None.') + header_base = '\n<<lightpurple>>{0:*^50}<<default>>\n' headers = [' ALL CHANGES ', ' REVIEW CHANGES ', ' APPROVED CHANGES '] - diff_by_letter_message = ('\x03{lightred}- o\n\x03{default}' - '\x03{lightred}- l\n\x03{default}' - '\x03{lightred}- d\n\x03{default}' - '\x03{lightgreen}+ n\n\x03{default}' - '\x03{lightgreen}+ e\n\x03{default}' - '\x03{lightgreen}+ w\n\x03{default}') + diff_by_letter_message = ('<<lightred>>- o\n<<default>>' + '<<lightred>>- l\n<<default>>' + '<<lightred>>- d\n<<default>>' + '<<lightgreen>>+ n\n<<default>>' + '<<lightgreen>>+ e\n<<default>>' + '<<lightgreen>>+ w\n<<default>>')
def check_headers(self, mock): """Check if all headers were added to output.""" diff --git a/tests/tools_formatter_tests.py b/tests/tools_formatter_tests.py index 20f0cdb..82c0a57 100755 --- a/tests/tools_formatter_tests.py +++ b/tests/tools_formatter_tests.py @@ -9,7 +9,7 @@ from contextlib import suppress
from pywikibot.tools import formatter -from tests.aspects import TestCase +from tests.aspects import DeprecationTestCase, TestCase
class TestListOutputter(TestCase): @@ -29,8 +29,7 @@ self.assertEqual(outputter.out, '\nfoo\nbar\n')
-# TODO: add tests for background colors. -class TestColorFormat(TestCase): +class TestColorFormat(DeprecationTestCase):
"""Test color_format function in bot module."""
@@ -49,6 +48,7 @@ result = formatter.color_format(format_string, *args, **kwargs) self.assertEqual(result, expected) self.assertIsInstance(result, type(expected)) + self.assertOneDeprecation()
def test_no_colors(self): """Test without colors in template string."""
pywikibot-commits@lists.wikimedia.org