diff --git a/pptx_blueprint/__init__.py b/pptx_blueprint/__init__.py index 309eac6..40226f6 100644 --- a/pptx_blueprint/__init__.py +++ b/pptx_blueprint/__init__.py @@ -1,5 +1,6 @@ import pathlib import pptx +import re from typing import Union, Iterable, Tuple from pptx.shapes.base import BaseShape @@ -23,6 +24,7 @@ def __init__(self, filename: _Pathlike) -> None: """ self._template_path = filename self._presentation = pptx.Presentation(filename) + self._copy_tags_to_name() pass def replace_text(self, label: str, new_text: str) -> None: @@ -71,7 +73,7 @@ def _find_shapes(self, matched_shapes = [] def _find_shapes_in_slide(slide): - return filter(lambda shape: shape.text == f'{{{tag_name}}}', slide.shapes) + return filter(lambda shape: shape.name == f'{{{tag_name}}}', slide.shapes) if slide_number == '*': slides = self._presentation.slides @@ -87,6 +89,21 @@ def _find_shapes_in_slide(slide): return matched_shapes + def _get_all_shapes(self) -> Iterable[BaseShape]: + # Do we need all the shapes? Perhaps we should filter on tags here. + all_shapes = [shape for slide in self._presentation.slides for shape in slide.shapes] + return all_shapes + + def _copy_tags_to_name(self) -> None: + all_shapes = self._get_all_shapes() + # This regex matches on tags + regex_tag = re.compile(r'^\s*(\{\w+\})\s*$') + for shape in all_shapes: + # We only copy contents we recognize as tags + match = regex_tag.match(shape.text) + if match: + shape.name = match.group(1) + def save(self, filename: _Pathlike) -> None: """Saves the updated pptx to the specified filepath. diff --git a/tests/test_template.py b/tests/test_template.py index a1ba1bd..d00a923 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -2,6 +2,7 @@ from pptx_blueprint import Template from pathlib import Path import pytest +import re @pytest.fixture @@ -38,3 +39,16 @@ def test_find_shapes_from_one_slide(template): def test_find_shapes_index_out_of_range(template): with pytest.raises(IndexError): shapes = template._find_shapes(0, 'logo') + +def test_get_all_shapes(template): + shapes = template._get_all_shapes() + for shape in shapes: + assert str(shape.text) and str(shape.name) + +def test_copy_tags_to_name(template): + template._copy_tags_to_name() + all_shapes = template._get_all_shapes() + regex_tag = re.compile(r'\{[\s\w]*\}') + for shape in all_shapes: + if regex_tag.match(shape.text): + assert shape.text == shape.name \ No newline at end of file