aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2015-09-12 16:06:21 +0100
committerMichael Williamson <mike@zwobble.org>2015-09-12 16:06:21 +0100
commit4c88820f3d4778e75a4be50f7a2d78d03dc86316 (patch)
treeaae9012c78c4f98f691c99adcded4693e67234d8
parent470ce2b5f07ed0191842db93bd5b653099c00aff (diff)
Add reading and writing of embedded style maps
-rw-r--r--mammoth/docx/style_map.py17
-rw-r--r--mammoth/zips.py6
-rw-r--r--tests/docx/style_map_tests.py34
3 files changed, 57 insertions, 0 deletions
diff --git a/mammoth/docx/style_map.py b/mammoth/docx/style_map.py
new file mode 100644
index 0000000..2841830
--- /dev/null
+++ b/mammoth/docx/style_map.py
@@ -0,0 +1,17 @@
+from ..zips import open_zip
+
+
+_style_map_path = "mammoth/style-map"
+
+
+def write_style_map(fileobj, style_map):
+ with open_zip(fileobj, "a") as zip_file:
+ zip_file.write_str(_style_map_path, style_map)
+
+
+def read_style_map(fileobj):
+ with open_zip(fileobj, "r") as zip_file:
+ if zip_file.exists(_style_map_path):
+ return zip_file.read_str(_style_map_path)
+
+
diff --git a/mammoth/zips.py b/mammoth/zips.py
index c6fe358..24c6b1c 100644
--- a/mammoth/zips.py
+++ b/mammoth/zips.py
@@ -26,3 +26,9 @@ class _Zip(object):
return True
except KeyError:
return False
+
+ def write_str(self, name, value):
+ self._zip_file.writestr(name, value)
+
+ def read_str(self, name):
+ return self._zip_file.read(name).decode("utf8")
diff --git a/tests/docx/style_map_tests.py b/tests/docx/style_map_tests.py
new file mode 100644
index 0000000..f298e1d
--- /dev/null
+++ b/tests/docx/style_map_tests.py
@@ -0,0 +1,34 @@
+import io
+
+from nose.tools import istest, assert_equal
+
+from mammoth.docx.style_map import write_style_map, read_style_map
+from mammoth.zips import open_zip
+
+
+@istest
+def reading_embedded_style_map_on_document_without_embedded_style_map_returns_none():
+ fileobj = _normal_docx()
+ assert_equal(None, read_style_map(fileobj))
+
+
+@istest
+def embedded_style_map_can_be_read_after_being_written():
+ fileobj = _normal_docx()
+ write_style_map(fileobj, "p => h1")
+ assert_equal("p => h1", read_style_map(fileobj))
+
+
+@istest
+def embedded_style_map_is_written_to_separate_file():
+ fileobj = _normal_docx()
+ write_style_map(fileobj, "p => h1")
+ with open_zip(fileobj, "r") as zip_file:
+ assert_equal("p => h1", zip_file.read_str("mammoth/style-map"))
+
+
+def _normal_docx():
+ fileobj = io.BytesIO()
+ with open_zip(fileobj, "w") as zip_file:
+ zip_file.write_str("placeholder", "placeholder")
+ return fileobj