You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
935 B
35 lines
935 B
1 year ago
|
import pathlib
|
||
|
import tarfile
|
||
|
from typing import IO
|
||
|
|
||
|
|
||
|
def create_tar_archive(fh: IO[bytes], directory: pathlib.Path):
|
||
|
"""Creates a tar archive of a directory"""
|
||
|
|
||
|
tar = tarfile.open(fileobj=fh, mode='w')
|
||
|
for file in directory.rglob("*"):
|
||
|
relative_path = str(file.relative_to(directory))
|
||
|
if file.is_symlink():
|
||
|
info = tarfile.TarInfo(relative_path)
|
||
|
info.type = tarfile.SYMTYPE
|
||
|
info.linkpath = str(file.readlink())
|
||
|
tar.addfile(info)
|
||
|
|
||
|
elif file.is_file():
|
||
|
info = tarfile.TarInfo(relative_path)
|
||
|
info.size = file.stat().st_size
|
||
|
info.type = tarfile.REGTYPE
|
||
|
with file.open('rb') as f:
|
||
|
tar.addfile(info, f)
|
||
|
|
||
|
tar.close()
|
||
|
fh.seek(0)
|
||
|
|
||
|
|
||
|
def extract_tar_archive(fh: IO[bytes], directory: pathlib.Path):
|
||
|
"""Extracts a tar archive to a directory"""
|
||
|
|
||
|
tar = tarfile.open(fileobj=fh, mode='r')
|
||
|
tar.extractall(str(directory), filter=lambda info, path: info)
|
||
|
tar.close()
|