1850a1951SThomas Huth# Utilities for python-based QEMU tests
2850a1951SThomas Huth#
3850a1951SThomas Huth# Copyright 2024 Red Hat, Inc.
4850a1951SThomas Huth#
5850a1951SThomas Huth# Authors:
6850a1951SThomas Huth#  Thomas Huth <thuth@redhat.com>
7850a1951SThomas Huth#
8850a1951SThomas Huth# This work is licensed under the terms of the GNU GPL, version 2 or
9850a1951SThomas Huth# later.  See the COPYING file in the top-level directory.
10850a1951SThomas Huth
11*e2e9fd25SThomas Huthimport lzma
12*e2e9fd25SThomas Huthimport os
13*e2e9fd25SThomas Huthimport shutil
14850a1951SThomas Huthimport tarfile
15850a1951SThomas Huth
16850a1951SThomas Huthdef archive_extract(archive, dest_dir, member=None):
17850a1951SThomas Huth    with tarfile.open(archive) as tf:
18850a1951SThomas Huth        if hasattr(tarfile, 'data_filter'):
19850a1951SThomas Huth            tf.extraction_filter = getattr(tarfile, 'data_filter',
20850a1951SThomas Huth                                           (lambda member, path: member))
21850a1951SThomas Huth        if member:
22850a1951SThomas Huth            tf.extract(member=member, path=dest_dir)
23850a1951SThomas Huth        else:
24850a1951SThomas Huth            tf.extractall(path=dest_dir)
25*e2e9fd25SThomas Huth
26*e2e9fd25SThomas Huthdef lzma_uncompress(xz_path, output_path):
27*e2e9fd25SThomas Huth    if os.path.exists(output_path):
28*e2e9fd25SThomas Huth        return
29*e2e9fd25SThomas Huth    with lzma.open(xz_path, 'rb') as lzma_in:
30*e2e9fd25SThomas Huth        try:
31*e2e9fd25SThomas Huth            with open(output_path, 'wb') as raw_out:
32*e2e9fd25SThomas Huth                shutil.copyfileobj(lzma_in, raw_out)
33*e2e9fd25SThomas Huth        except:
34*e2e9fd25SThomas Huth            os.remove(output_path)
35*e2e9fd25SThomas Huth            raise
36