1# Utilities for python-based QEMU tests 2# 3# Copyright 2024 Red Hat, Inc. 4# 5# Authors: 6# Thomas Huth <thuth@redhat.com> 7# 8# This work is licensed under the terms of the GNU GPL, version 2 or 9# later. See the COPYING file in the top-level directory. 10 11import gzip 12import lzma 13import os 14import shutil 15import subprocess 16import tarfile 17 18def archive_extract(archive, dest_dir, member=None): 19 with tarfile.open(archive) as tf: 20 if hasattr(tarfile, 'data_filter'): 21 tf.extraction_filter = getattr(tarfile, 'data_filter', 22 (lambda member, path: member)) 23 if member: 24 tf.extract(member=member, path=dest_dir) 25 else: 26 tf.extractall(path=dest_dir) 27 28def gzip_uncompress(gz_path, output_path): 29 if os.path.exists(output_path): 30 return 31 with gzip.open(gz_path, 'rb') as gz_in: 32 try: 33 with open(output_path, 'wb') as raw_out: 34 shutil.copyfileobj(gz_in, raw_out) 35 except: 36 os.remove(output_path) 37 raise 38 39def lzma_uncompress(xz_path, output_path): 40 if os.path.exists(output_path): 41 return 42 with lzma.open(xz_path, 'rb') as lzma_in: 43 try: 44 with open(output_path, 'wb') as raw_out: 45 shutil.copyfileobj(lzma_in, raw_out) 46 except: 47 os.remove(output_path) 48 raise 49 50def cpio_extract(cpio_handle, output_path): 51 cwd = os.getcwd() 52 os.chdir(output_path) 53 subprocess.run(['cpio', '-i'], 54 input=cpio_handle.read(), 55 stderr=subprocess.DEVNULL) 56 os.chdir(cwd) 57