import logging as logger
import os
import tarfile


def zip_file(from_path, to_path):
    parentDir = os.path.abspath(os.path.dirname(from_path) + os.path.sep + ".")
    with tarfile.open(to_path, 'w:gz') as zipFile:
        for root, dirs, files in os.walk(from_path, topdown=True):
            for name in files:
                try:
                    absPath = os.path.join(root, name)  # 文件绝对路径
                    arcname = os.path.relpath(absPath, parentDir)  # 文件相对路径
                    if not os.path.exists(absPath):
                        continue
                    zipFile.add(absPath, arcname)
                except Exception as e:
                    logger.debug(e)
                    pass


def unzip_file(from_path, to_path):
    if to_path is None:
        end = from_path.rfind('/')
        if end < 0:
            end = from_path.rfind('\\')
        to_path = from_path[0:end]
    tar = tarfile.open(from_path, 'r:gz')
    tar.extractall(to_path)
    tar.close()
