diff options
| -rw-r--r-- | mammoth/docx/__init__.py | 6 | ||||
| -rw-r--r-- | mammoth/zips.py | 12 | ||||
| -rw-r--r-- | tests/zips_tests.py | 30 |
3 files changed, 45 insertions, 3 deletions
diff --git a/mammoth/docx/__init__.py b/mammoth/docx/__init__.py index a71ca0c..2bee161 100644 --- a/mammoth/docx/__init__.py +++ b/mammoth/docx/__init__.py @@ -1,7 +1,7 @@ from functools import partial import os -from .. import results, lists +from .. import results, lists, zips from .document_xml import read_document_xml_element from .content_types_xml import empty_content_types, read_content_types_xml_element from .relationships_xml import read_relationships_xml_element, Relationships @@ -125,8 +125,8 @@ def _part_with_body_reader(document_path, zip_file): def _find_relationships_path_for(name): - parts = name.split("/") - return "/".join(parts[:-1] + ["_rels/" + parts[-1] + ".rels"]) + dirname, basename = zips.split_path(name) + return zips.join_path(dirname, "_rels", basename + ".rels") def _read_relationships(zip_file, name): diff --git a/mammoth/zips.py b/mammoth/zips.py index 432be5d..cca0b49 100644 --- a/mammoth/zips.py +++ b/mammoth/zips.py @@ -54,3 +54,15 @@ def update_zip(fileobj, files): fileobj.seek(0) destination_fileobj.seek(0) shutil.copyfileobj(destination_fileobj, fileobj) + + +def split_path(path): + parts = path.rsplit("/", 1) + if len(parts) == 1: + return ("", path) + else: + return tuple(parts) + + +def join_path(*args): + return "/".join(list(filter(None, args))) diff --git a/tests/zips_tests.py b/tests/zips_tests.py new file mode 100644 index 0000000..671b5cb --- /dev/null +++ b/tests/zips_tests.py @@ -0,0 +1,30 @@ +from nose.tools import istest, assert_equal + +from mammoth import zips + + +@istest +def split_path_splits_zip_paths_on_last_forward_slash(): + assert_equal(("a", "b"), zips.split_path("a/b")) + assert_equal(("a/b", "c"), zips.split_path("a/b/c")) + assert_equal(("/a/b", "c"), zips.split_path("/a/b/c")) + + +@istest +def when_path_has_no_forward_slashes_then_split_path_returns_empty_dirname(): + assert_equal(("", "name"), zips.split_path("name")) + + +@istest +def join_path_joins_arguments_with_forward_slashes(): + assert_equal("a/b", zips.join_path("a", "b")) + assert_equal("a/b/c", zips.join_path("a/b", "c")) + assert_equal("/a/b/c", zips.join_path("/a/b", "c")) + + +@istest +def empty_parts_are_ignored_when_joining_paths(): + assert_equal("a", zips.join_path("", "a")) + assert_equal("b", zips.join_path("", "b")) + assert_equal("a/b", zips.join_path("a", "", "b")) + |
