1cfcb4484SDaniel P. Berrangé# SPDX-License-Identifier: GPL-2.0-or-later 2cfcb4484SDaniel P. Berrangé# 3cfcb4484SDaniel P. Berrangé# Utilities for python-based QEMU tests 4cfcb4484SDaniel P. Berrangé# 5cfcb4484SDaniel P. Berrangé# Copyright 2024 Red Hat, Inc. 6cfcb4484SDaniel P. Berrangé# 7cfcb4484SDaniel P. Berrangé# Authors: 8cfcb4484SDaniel P. Berrangé# Thomas Huth <thuth@redhat.com> 9cfcb4484SDaniel P. Berrangé 10cfcb4484SDaniel P. Berrangéimport os 11cfcb4484SDaniel P. Berrangéimport subprocess 12cfcb4484SDaniel P. Berrangéimport tarfile 13379ee839SDaniel P. Berrangéimport zipfile 14cfcb4484SDaniel P. Berrangé 15*512fe088SDaniel P. Berrangéfrom .cmd import run_cmd 16*512fe088SDaniel P. Berrangé 17cfcb4484SDaniel P. Berrangé 18cfcb4484SDaniel P. Berrangédef tar_extract(archive, dest_dir, member=None): 19cfcb4484SDaniel P. Berrangé with tarfile.open(archive) as tf: 20cfcb4484SDaniel P. Berrangé if hasattr(tarfile, 'data_filter'): 21cfcb4484SDaniel P. Berrangé tf.extraction_filter = getattr(tarfile, 'data_filter', 22cfcb4484SDaniel P. Berrangé (lambda member, path: member)) 23cfcb4484SDaniel P. Berrangé if member: 24cfcb4484SDaniel P. Berrangé tf.extract(member=member, path=dest_dir) 25cfcb4484SDaniel P. Berrangé else: 26cfcb4484SDaniel P. Berrangé tf.extractall(path=dest_dir) 27cfcb4484SDaniel P. Berrangé 28cfcb4484SDaniel P. Berrangédef cpio_extract(cpio_handle, output_path): 29cfcb4484SDaniel P. Berrangé cwd = os.getcwd() 30cfcb4484SDaniel P. Berrangé os.chdir(output_path) 31cfcb4484SDaniel P. Berrangé subprocess.run(['cpio', '-i'], 32cfcb4484SDaniel P. Berrangé input=cpio_handle.read(), 33cfcb4484SDaniel P. Berrangé stderr=subprocess.DEVNULL) 34cfcb4484SDaniel P. Berrangé os.chdir(cwd) 35379ee839SDaniel P. Berrangé 36379ee839SDaniel P. Berrangédef zip_extract(archive, dest_dir, member=None): 37379ee839SDaniel P. Berrangé with zipfile.ZipFile(archive, 'r') as zf: 38379ee839SDaniel P. Berrangé if member: 39379ee839SDaniel P. Berrangé zf.extract(member=member, path=dest_dir) 40379ee839SDaniel P. Berrangé else: 41379ee839SDaniel P. Berrangé zf.extractall(path=dest_dir) 42*512fe088SDaniel P. Berrangé 43*512fe088SDaniel P. Berrangédef deb_extract(archive, dest_dir, member=None): 44*512fe088SDaniel P. Berrangé cwd = os.getcwd() 45*512fe088SDaniel P. Berrangé os.chdir(dest_dir) 46*512fe088SDaniel P. Berrangé try: 47*512fe088SDaniel P. Berrangé (stdout, stderr, ret) = run_cmd(['ar', 't', archive]) 48*512fe088SDaniel P. Berrangé file_path = stdout.split()[2] 49*512fe088SDaniel P. Berrangé run_cmd(['ar', 'x', archive, file_path]) 50*512fe088SDaniel P. Berrangé tar_extract(file_path, dest_dir, member) 51*512fe088SDaniel P. Berrangé finally: 52*512fe088SDaniel P. Berrangé os.chdir(cwd) 53