compress.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2015, Ansgar Burchardt <ansgar@debian.org>
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along
  14. # with this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. """
  17. Helper methods to deal with (de)compressing files
  18. """
  19. import os
  20. import shutil
  21. import subprocess
  22. from typing import IO, Optional
  23. def decompress_zstd(input: IO, output: IO) -> None:
  24. subprocess.check_call(["zstd", "--decompress"], stdin=input, stdout=output)
  25. def decompress_xz(input: IO, output: IO) -> None:
  26. subprocess.check_call(["xz", "--decompress", "-T0"], stdin=input, stdout=output)
  27. def decompress_bz2(input: IO, output: IO) -> None:
  28. subprocess.check_call(["bzip2", "--decompress"], stdin=input, stdout=output)
  29. def decompress_gz(input: IO, output: IO) -> None:
  30. subprocess.check_call(["gzip", "--decompress"], stdin=input, stdout=output)
  31. decompressors = {
  32. '.zst': decompress_zstd,
  33. '.xz': decompress_xz,
  34. '.bz2': decompress_bz2,
  35. '.gz': decompress_gz,
  36. }
  37. def decompress(input: IO, output: IO, filename: Optional[str] = None) -> None:
  38. if filename is None:
  39. filename = input.name
  40. base, ext = os.path.splitext(filename)
  41. decompressor = decompressors.get(ext, None)
  42. if decompressor is not None:
  43. decompressor(input, output)
  44. else:
  45. shutil.copyfileobj(input, output)