Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- import mmap
- import subprocess
- import sys
- from argparse import ArgumentParser
- from bz2 import BZ2File
- from gzip import GzipFile
- from lzma import LZMAFile
- from pathlib import Path
- def compressor(source: Path, target: Path, CompressClass, buffer_size=1024 ** 2):
- with CompressClass(target, "w") as target, source.open("rb") as source:
- buffer = bytearray(buffer_size)
- view = memoryview(buffer)
- while True:
- size = source.readinto(buffer)
- if size == 0:
- break
- target.write(view[:size])
- def hasher(algo, files):
- result = []
- for file in files:
- with file.open("rb") as fd:
- with mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) as mm:
- dig = hashlib.new(algo, mm).hexdigest()
- result.append(f"{dig} {file.name}")
- result = "\n".join(result)
- with open(f"{files[0].stem}.{algo}", "w") as hash_file:
- hash_file.write(result)
- def compress(image):
- bz2 = image.with_suffix(".img.bz2")
- xz = image.with_suffix(".img.xz")
- gz = image.with_suffix(".img.gz")
- md5 = image.with_suffix(".md5")
- sha256 = image.with_suffix(".sha256")
- print(f"Komprimiere {bz2}")
- # with bz2.open("wb") as fd:
- # subprocess.run(["bzip2", "-c", "-9", "-k", str(image)], stdout=fd)
- compressor(image, bz2, BZ2File)
- print(f"Komprimiere {xz}")
- # with xz.open("wb") as fd:
- # subprocess.run(["xz", "-c", "-9", "-k", str(image)], stdout=fd)
- compressor(image, xz, LZMAFile)
- print(f"Komprimiere {gz}")
- compressor(image, gz, GzipFile)
- print("Erstelle md5sum")
- hasher("md5", [image, bz2, gz, xz])
- # with md5.open("wb") as fd:
- # subprocess.run(["md5sum", str(image), str(bz2), str(xz)], stdout=fd)
- print("Erstelle sha256sum")
- hasher("sha256", [image, bz2, gz, xz])
- # with sha256.open("wb") as fd:
- # subprocess.run(["sha256sum", str(image), str(bz2), str(xz)], stdout=fd)
- def main(image):
- if not image.exists():
- raise ValueError("Image file does not exist.")
- compress(image)
- def get_args():
- parser = ArgumentParser()
- parser.add_argument("file", type=Path, help="Image to compress")
- return parser.parse_args()
- if __name__ == "__main__":
- args = get_args()
- main(args.file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement