Source code for wikibaseintegrator.wbi_editgroups

"""
Support of the EditGroups tool (https://www.wikidata.org/wiki/Wikidata:Edit_groups), which tracks the edits of a bot as
a batch that can be reviewed, discussed and reverted at once.

EditGroups recognizes the edits of a custom bot from a link to the batch at the end of the edit summary, see
https://www.wikidata.org/wiki/Wikidata:Edit_groups/Adding_a_tool#For_custom_bots
"""
from __future__ import annotations

import re
import secrets

# The batch identifier of a custom bot: from 4 to 32 lowercase hexadecimal digits
BATCH_ID_PATTERN = re.compile(r'^[0-9a-f]{4,32}$')

# MediaWiki limits an edit summary to 500 characters, and Wikibase prefixes the summary with an automatic comment (e.g.
# '/* wbeditentity-update-languages-and-other-short:0||fr */'). The text is shortened to keep the batch link, which
# must stay intact for EditGroups to recognize the edit.
MAX_SUMMARY_LENGTH = 400


[docs] class EditGroup: """ An EditGroups batch of a custom bot. Add the batch link to the summary of every edit of the batch:: editgroup = EditGroup() item.write(summary=editgroup.summary('Add the population')) The batch is then listed on https://editgroups.toolforge.org/ once the first edit is made. """ def __init__(self, batch_id: str | None = None) -> None: """ :param batch_id: The identifier of the batch, from 4 to 32 lowercase hexadecimal digits. A random one is generated by default. Reuse the same identifier to add edits to an existing batch. """ if batch_id is None: batch_id = secrets.token_hex(6) if not BATCH_ID_PATTERN.match(batch_id): raise ValueError(f"Invalid EditGroups batch ID ({batch_id}), it must be made of 4 to 32 lowercase hexadecimal digits") self.batch_id = batch_id @property def link(self) -> str: """The wikilink to the batch, as EditGroups expects it in the edit summary.""" return f'([[:toolforge:editgroups/b/CB/{self.batch_id}|details]])' @property def url(self) -> str: """The URL of the batch on EditGroups.""" return f'https://editgroups.toolforge.org/b/CB/{self.batch_id}/'
[docs] def summary(self, summary: str | None = None) -> str: """ Return the edit summary with the batch link appended. :param summary: The edit summary. It is shortened if needed, so that the batch link is never truncated. :return: The edit summary to use for an edit of the batch. """ if not summary: return self.link max_length = MAX_SUMMARY_LENGTH - len(self.link) - 1 if len(summary) > max_length: summary = summary[:max_length - 1].rstrip() + '…' return f'{summary} {self.link}'
def __str__(self) -> str: return self.batch_id def __repr__(self) -> str: return f'<EditGroup {self.batch_id}>'