1#!/usr/bin/env python3
2# vim: set syntax=python ts=4 :
3# Copyright (c) 2020 Intel Corporation
4# SPDX-License-Identifier: Apache-2.0
5
6import json
7import os
8import tarfile
9
10from twisterlib.statuses import TwisterStatus
11
12
13class Artifacts:
14    """Package the test artifacts into a tarball."""
15    def __init__(self, env):
16        self.options = env.options
17
18    def make_tarfile(self, output_filename, source_dirs):
19        """Create a tarball from the test artifacts."""
20        root = os.path.basename(self.options.outdir)
21        with tarfile.open(output_filename, "w:bz2") as tar:
22            tar.add(self.options.outdir, recursive=False)
23            for d in source_dirs:
24                f = os.path.relpath(d, self.options.outdir)
25                tar.add(d, arcname=os.path.join(root, f))
26
27    def package(self):
28        """Package the test artifacts into a tarball."""
29        dirs = []
30        with open(
31            os.path.join(self.options.outdir, "twister.json"), encoding='utf-8'
32        ) as json_test_plan:
33            jtp = json.load(json_test_plan)
34            for t in jtp['testsuites']:
35                if t['status'] != TwisterStatus.FILTER:
36                    p = t['platform']
37                    normalized  = p.replace("/", "_")
38                    dirs.append(
39                        os.path.join(
40                            self.options.outdir, normalized, t['toolchain'], t['name']
41                        )
42                    )
43
44        dirs.extend(
45            [
46                os.path.join(self.options.outdir, "twister.json"),
47                os.path.join(self.options.outdir, "testplan.json")
48                ]
49            )
50        self.make_tarfile(self.options.package_artifacts, dirs)
51