示例#1
0
    def test_loc_objloc(self):
        loc = Template('Object location')
        loc.add(1, "one")
        set_location(self.tree, None)
        set_object_location(self.tree, loc)
        # Might be better without the spurious newline, but this will do.
        self.assertEqual(
            str(self.tree), """
== {{int:filedesc}} ==
{{Information
|description={{en|1=Street Waste Bin Waste bin on the street outside Crosby and Blundellsands Station}}
|date=2010-04-11
|source=From [http://www.geograph.org.uk/photo/1801330 geograph.org.uk]
|author=[http://www.geograph.org.uk/profile/46411 Paul Glover]
|permission=
|other_versions=
}}
{{Object location|one}}


== {{int:license-header}} ==
{{Geograph|1801330|Paul Glover}}

[[Category:Streets in Sefton]]
[[Category:Geograph images in Merseyside]]
""")
示例#2
0
    def backup_template(self, template: Template, page: Union[str, Page],
                        key: Union[str, List[str]]):
        """
        Backs up a template in the `Backup` namespace. The template can later be restored with `get_restored_template`.
        :param template: Template object
        :param page: Page or title where the template is located on
        :param key: Identifying set of params that we can use to locate the template when we restore it
        :return: null
        """
        if isinstance(page, str):
            page = self.client.pages[page]
        if isinstance(key, str):
            key = [key]
        key_template = Template('BackupKey')
        for key_param in key:
            key_template.add(key_param,
                             template.get(key_param, Parameter('', '')).value)

        # this method will be used in TemplateModifier so it is essential that
        # we do not modify the original
        copy_template = copy.deepcopy(template)
        copy_template.add('backup_key', str(key_template))
        self.client.pages['Backup:' + page.name].append('\n' +
                                                        str(copy_template),
                                                        contentmodel='text')
示例#3
0
 def test_objloc(self):
     loc = Template('Object location')
     loc.add(1, "one")
     set_object_location(self.tree, loc)
     self.assertEqual(
         str(self.tree),
         "{{Information}}\n{{location dec}}\n{{Object location|one}}")
示例#4
0
    def format(self, citation: Citation):
        tname = CiteTemplate.TEMPLATE_FALLBACK.get(
            citation.type, CiteTemplate.TEMPLATE_FALLBACK['default'])
        template = Template(tname)

        for fragment in CiteTemplate.ORDER:
            func = getattr(self, '_fragment_' + fragment, None)
            if func:
                func(template, citation)
            elif fragment in citation:
                template.add(fragment, str(citation[fragment]))

        return str(template)
示例#5
0
    def to_mediawiki_template(self, maccabi_games: MaccabiGamesStats) -> str:
        tag_paper_template = Template(f'{_PAPER_TAG_TEMPLATE_NAME}\n')

        tag_paper_template.add(_PAPER_NAME_PARAM_NAME, f'{self.paper_name}\n')

        if self.paper_publish_date is not None:
            tag_paper_template.add(
                _PAPER_PUBLISH_DATE_PARAM_NAME,
                f'{self.paper_publish_date.strftime("%d-%m-%Y")}\n')

            if math.fabs((self.paper_publish_date -
                          self.paper_related_game_date).days) > 7:
                raise RuntimeError(
                    f'There is more than a week between the publish and the game date, is it an error?'
                )

        potential_games = maccabi_games.played_at(self.paper_related_game_date)
        if len(potential_games) != 1:
            raise RuntimeError(
                f'Could not match exactly one game for date: {self.paper_related_game_date}, '
                f'found these games: {potential_games}')

        game_page_name = _generate_page_name_from_game(potential_games[0])
        tag_paper_template.add(_PAPER_RELATED_GAME_PARAM_NAME,
                               f'{game_page_name}')

        return str(tag_paper_template)
示例#6
0
    def format(self, citation: Citation):
        tname = CiteTemplate.TEMPLATE_FALLBACK.get(
            citation.type,
            CiteTemplate.TEMPLATE_FALLBACK['default']
        )
        template = Template(tname)

        for fragment in CiteTemplate.ORDER:
            func = getattr(self, '_fragment_' + fragment, None)
            if func:
                func(template, citation)
            elif fragment in citation:
                template.add(fragment, str(citation[fragment]))

        return str(template)
示例#7
0
def combine_template_chains(wc: Wikicode, new_template_name: str,
                            template_indices: List[int],
                            text_indices: List[int]) -> None:
    """
    Helper function for combining templates that are linked via free text into
    a structured template hierarchy.
    """
    index_combos = []

    index_combo = []
    combine = False
    for i in template_indices:
        if (i + 1 in text_indices) or (i - 2 in index_combo and combine):
            index_combo.append(i)

        combine = i + 1 in text_indices
        if not combine:
            if len(index_combo) > 1:
                index_combos.append(index_combo)
            index_combo = []

    if len(index_combo) > 1:
        index_combos.append(index_combo)

    combo_nodes = [[wc.nodes[i] for i in chain] for chain in index_combos]

    for combo in combo_nodes:
        params = [
            Parameter(str(i + 1), t, showkey=False)
            for i, t in enumerate(combo)
        ]
        new_template = Template(new_template_name, params=params)
        wc.insert_before(combo[0], new_template, recursive=False)
        for node in combo:
            wc.remove(node, recursive=False)
示例#8
0
def merge_etyl_templates(wc: Wikicode) -> Wikicode:
    """
    Given a chunk of wikicode, finds instances where the deprecated `etyl` template is immediately followed by
    either a word in free text, a linked word, or a generic `mention`/`link`/`langname-mention` template.
    It replaces this pattern with a new `derived-parsed` template -- meaning the same thing as the `derived` template
    but namespaced to differentiate. For cases where the `mention` language is different from the `etyl` language,
    we use the former. The template is removed if we can't parse it effectively.
    """
    etyl_indices = [
        i for i, node in enumerate(wc.nodes) if isinstance(node, Template)
        and node.name == "etyl" and i < len(wc.nodes) - 1
    ]

    nodes_to_remove = []
    for i in etyl_indices:
        make_new_template = False
        etyl: Template = wc.nodes[i]
        related_language = etyl.params[0]
        if len(etyl.params) == 1:
            language = "en"
        else:
            language = etyl.params[1]
        node = wc.nodes[i + 1]
        if isinstance(node, Text):
            val = re.split(",| |", node.value.strip())[0]
            if val:
                make_new_template = True
        elif isinstance(node, Wikilink):
            val = node.text or node.title
            val = re.split(",| |", val.strip())[0]
            if val:
                make_new_template = True
        elif isinstance(node, Template):
            if node.name in ("m", "mention", "m+", "langname-mention", "l",
                             "link"):
                related_language = node.params[0]
                if len(node.params) > 1:
                    val = node.params[1].value
                    make_new_template = True
                    nodes_to_remove.append(node)

        if make_new_template:
            params = [
                Parameter(str(i + 1), str(param), showkey=False)
                for i, param in enumerate([language, related_language, val])
            ]
            new_template = Template("derived-parsed", params=params)
            wc.replace(etyl, new_template, recursive=False)
        else:
            nodes_to_remove.append(etyl)

    for node in nodes_to_remove:
        wc.remove(node, recursive=False)
    return wc
示例#9
0
    def get_restored_template(
            self, template: Template, page: Union[str, Page],
            key: Union[str, List[str]]) -> Optional[Template]:
        """
        Looks for the backed-up version of the specified template on the backup page & returns it

        The template should have been backed up using the backup_template method earlier.

        :param template: Template object that we want to restore from backup page
        :param page: Page or title where the template is located on
        :param key: Identifying set of params to use to restore the template from
        :return: Template object, if found, else None
        """
        if isinstance(page, str):
            page = self.client.pages[page]
        if isinstance(key, str):
            key = [key]
        backup_text = self.client.pages['Backup:' + page.name].text()
        for backup_template in mwparserfromhell.parse(
                backup_text).filter_templates():
            if not backup_template.name.matches(template.name):
                continue

            # kinda need to do a hack to get this as a template
            backup_key_str = str(backup_template.get('backup_key').value)
            backup_key_wikitext = mwparserfromhell.parse(backup_key_str)
            backup_key = None
            for tl in backup_key_wikitext.filter_templates():
                if tl.name.matches('BackupKey'):
                    backup_key = tl
                    break
            # now backup_key is a template value of BackupKey

            is_match = True
            i = 0
            for param in backup_key.params:
                name = param.name.strip()
                if name in key:
                    if param.value.strip() == template.get(
                            name, Parameter('', '')).value.strip():
                        i += 1
                else:
                    is_match = False
            if i == len(key) and is_match:
                return backup_template
        return None
示例#10
0
	def update_plaintext(self):
		print('starting page ' + self.current_page.name)
		chromas = []
		price = ''
		release = ''
		template_list = self.current_wikitext.filter_templates()
		for infobox in template_list:
			infobox: Template
			if infobox.name.matches('ChromaSet'):
				self.current_wikitext.remove(infobox)
				self.current_text = str(self.current_wikitext)
				self.current_text = self.current_text.replace('== Chromas ==', '')
			if not infobox.name.matches('Infobox Skin'):
				continue
			if not infobox.has('chroma'):
				return
			if infobox.has('chroma_rp'):
				price = infobox.get('chroma_rp').value.strip()
			if infobox.has('chroma_date'):
				release = infobox.get('chroma_date').value.strip()
			param = infobox.get('chroma').value
			for tl in param.filter_templates():
				if not tl.name.matches('ChromaBox'):
					continue
				i = 1
				while tl.has('chroma' + str(i)):
					s = str(i)
					new_chroma = Template('ChromaSet/Line')
					add_param(new_chroma, tl, s, '')
					add_param(new_chroma, tl, s, 'hex1')
					add_param(new_chroma, tl, s, 'hex2')
					add_param(new_chroma, tl, s, 'name')
					add_param(new_chroma, tl, s, 'rp')
					add_special_param(new_chroma, tl, s)
					chromas.append(str(new_chroma))
					i += 1
		chroma_section = ['== Chromas ==', '{{{{ChromaSet|price={}|release={}'.format(price, release)]
		for chroma in chromas:
			chroma_section.append('|' + chroma)
		chroma_section.append('}}')
		self.current_text = self.current_text.replace(
			'{{ChampionSkinImageSections}}',
			'\n'.join(chroma_section) + '\n' + '{{ChampionSkinImageSections}}'
		)
		self.current_text = self.current_text.replace('\n\n\n', '\n')
		self.current_text = self.current_text.replace('\n\n', '\n')
示例#11
0
def location_from_grid(grid,
                       e,
                       n,
                       digits,
                       view_direction,
                       use6fig,
                       mapit=None):
    latstr, lonstr, prec = latlon_from_grid(grid, e, n, digits, use6fig)
    precstr = "{:g}".format(prec)
    paramstr = "source:" + source_from_grid(grid, e, n, digits)
    region = region_of(grid, e, n, latstr, lonstr, mapit)
    if region != None:
        paramstr += "_region:{}".format(region)
    if view_direction != None:
        paramstr += "_heading:{}".format(view_direction)
    t = Template(mwparserfromhell.parse('Location'))
    t.add(1, latstr)
    t.add(2, lonstr)
    t.add(3, paramstr)
    t.add('prec', precstr)
    return t
示例#12
0
def get_football_stadium_template_object():
    return Template(stadium_template_name)
示例#13
0
 def __init__(self):
     self._template = Template(self.get_name())
     self._parameters = []
     self._parameters_map = {}
def get_football_player_template_object():
    return Template(player_template_name)
示例#15
0
def get_football_team_template_object():
    return Template(team_template_name)
示例#16
0
 def test_loc(self):
     loc = Template('Location')
     loc.add(1, "one")
     set_location(self.tree, loc)
     self.assertEqual(str(self.tree),
                      "{{Location|one}}\n{{object location}}")
def get_football_games_template_object():
    return Template(football_games_template_name)
示例#18
0
def get_football_referee_template_object():
    return Template(referee_template_name)