update bag: apply suggestions for improvement
More specific error messages, pathlib instead of os, contextmanager
for temporary directory
from datetime import datetime
from os import makedirs, chdir, walk
-from os.path import join, isdir, basename, exists, relpath, isfile
+from os.path import join, isdir, basename, exists, relpath
+from pathlib import Path
from shutil import make_archive, rmtree, copyfile, move
-from tempfile import mkdtemp
+from tempfile import mkdtemp, TemporaryDirectory
import re
import tempfile
import sys
from bagit import Bag, make_manifests, _load_tag_file, _make_tag_file, _make_tagmanifest_file # pylint: disable=no-name-in-module
from distutils.dir_util import copy_tree
+from contextlib import nullcontext
from ocrd_utils import (
pushd_popd,
@@ -291,30 +293,23 @@ class WorkspaceBagger():
raise Exception("Setting 'dest' and 'overwrite' is a contradiction")
if not overwrite and not dest:
raise Exception("For checksum recreation 'dest' must be provided")
-
- if not exists(src):
+ src_path = Path(src)
+ if not src_path.exists():
raise Exception("Path to bag not existing")
- is_zipped = isfile(src)
+ is_zipped = src_path.is_file()
+ with TemporaryDirectory() if is_zipped else nullcontext() as tempdir:
if is_zipped:
- tmp_path = mkdtemp()
- unzip_file_to_dir(src, tmp_path)
- path_to_bag = tmp_path
- if not exists(join(path_to_bag, "data")):
- try:
- rmtree(tmp_path)
- except OSError:
- pass
- raise Exception("data-dir of bag not found")
+ unzip_file_to_dir(src, tempdir)
+ path_to_bag = Path(tempdir)
+ if not path_to_bag.joinpath("data").exists():
+ raise FileNotFoundError("data directory of bag not found")
else:
- path_to_bag = src if overwrite else dest
- if not exists(join(src, "data")):
- raise Exception("data-dir of bag not found")
+ path_to_bag = src_path if overwrite else Path(dest)
+ if not src_path.joinpath("data").exists():
+ raise FileNotFoundError(f"data directory of bag not found at {src}")
if not overwrite:
- makedirs(dest, exist_ok=True)
- # TODO: write test for copytree. Expected behaviour: src contains stuff. dest is a
- # non existing dir. afterwards dest has all files/folder contained in src but
- # not src itself. Same if dest exists
+ path_to_bag.mkdir(parents=True, exist_ok=True)
copy_tree(src, dest)
with pushd_popd(path_to_bag):
@@ -326,7 +321,7 @@ class WorkspaceBagger():
_make_tagmanifest_file("sha512", ".")
if is_zipped:
- name = basename(src)
+ name = src_path.name
if name.endswith(".zip"):
name = name[:-4]
zip_path = make_archive(name, "zip", path_to_bag)
