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 lzma
12import os
13import shutil
14import tarfile
15
16def archive_extract(archive, dest_dir, member=None):
17    with tarfile.open(archive) as tf:
18        if hasattr(tarfile, 'data_filter'):
19            tf.extraction_filter = getattr(tarfile, 'data_filter',
20                                           (lambda member, path: member))
21        if member:
22            tf.extract(member=member, path=dest_dir)
23        else:
24            tf.extractall(path=dest_dir)
25
26def lzma_uncompress(xz_path, output_path):
27    if os.path.exists(output_path):
28        return
29    with lzma.open(xz_path, 'rb') as lzma_in:
30        try:
31            with open(output_path, 'wb') as raw_out:
32                shutil.copyfileobj(lzma_in, raw_out)
33        except:
34            os.remove(output_path)
35            raise
36