Created
March 27, 2024 12:00
-
-
Save pszemraj/6315dfed69a2b1e80e4b26f4c77baf2b to your computer and use it in GitHub Desktop.
simple CLI for builtin-python archive creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Creates an archive of a directory | |
pip install fire | |
""" | |
import os | |
import shutil | |
from pathlib import Path | |
import fire | |
def archive_dir( | |
dir_path: os.PathLike, | |
archive_path: os.PathLike = None, | |
format: str = ".zip", | |
verbose: bool = True, | |
) -> Path: | |
""" | |
archive_dir - Creates an archive of a directory | |
:param os.PathLike dir_path: _description_ | |
:param os.PathLike archive_path: where to save the archive | |
:param str format: the format of the archive, defaults to ".zip" | |
:return Path: the path to the archive | |
""" | |
dir_path = Path(dir_path) | |
if not dir_path.is_dir(): | |
raise ValueError(f"{dir_path} is not a valid directory.") | |
if archive_path is None: | |
archive_path = dir_path.parent / f"{dir_path.name}{format}" | |
else: | |
archive_path = Path(archive_path) | |
if archive_path.suffix != format: | |
archive_path = archive_path.with_suffix(format) | |
if format == ".tar.gz": | |
archive_format = "gztar" | |
elif format == ".tar.bz2": | |
archive_format = "bztar" | |
elif format == ".tar": | |
archive_format = "tar" | |
elif format == ".zip": | |
archive_format = "zip" | |
else: | |
raise ValueError(f"Unsupported archive format: {format}") | |
shutil.make_archive( | |
archive_path.parent / archive_path.name.replace(format, ""), | |
archive_format, | |
dir_path, | |
verbose=verbose, | |
) | |
return archive_path | |
if __name__ == "__main__": | |
fire.Fire(archive_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment