1##
2# Copyright (c) Microsoft Corporation.
3# SPDX-License-Identifier: BSD-2-Clause-Patent
4##
5import os
6import logging
7import json
8
9try:
10    from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin
11
12    class BuildToolsReportGenerator(IUefiBuildPlugin):
13        def do_report(self, thebuilder):
14            try:
15                from edk2toolext.environment import version_aggregator
16            except ImportError:
17                logging.critical("Loading BuildToolsReportGenerator failed, please update your Edk2-PyTool-Extensions")
18                return 0
19
20            OutputReport = os.path.join(thebuilder.env.GetValue("BUILD_OUTPUT_BASE"), "BUILD_TOOLS_REPORT")
21            OutputReport = os.path.normpath(OutputReport)
22            if not os.path.isdir(os.path.dirname(OutputReport)):
23                os.makedirs(os.path.dirname(OutputReport))
24
25            Report = BuildToolsReport()
26            Report.MakeReport(version_aggregator.GetVersionAggregator().GetAggregatedVersionInformation(), OutputReport=OutputReport)
27
28        def do_pre_build(self, thebuilder):
29            self.do_report(thebuilder)
30            return 0
31
32        def do_post_build(self, thebuilder):
33            self.do_report(thebuilder)
34            return 0
35
36except ImportError:
37    pass
38
39
40class BuildToolsReport(object):
41    MY_FOLDER = os.path.dirname(os.path.realpath(__file__))
42    VERSION = "1.00"
43
44    def __init__(self):
45        pass
46
47    def MakeReport(self, BuildTools, OutputReport="BuildToolsReport"):
48        logging.info("Writing BuildToolsReports to {0}".format(OutputReport))
49        versions_list = []
50        for key, value in BuildTools.items():
51            versions_list.append(value)
52        versions_list = sorted(versions_list, key=lambda k: k['type'])
53        json_dict = {"modules": versions_list,
54                     "PluginVersion": BuildToolsReport.VERSION}
55
56        htmlfile = open(OutputReport + ".html", "w")
57        jsonfile = open(OutputReport + ".json", "w")
58        template = open(os.path.join(BuildToolsReport.MY_FOLDER, "BuildToolsReport_Template.html"), "r")
59
60        for line in template.readlines():
61            if "%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%" in line:
62                line = line.replace("%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%", json.dumps(json_dict))
63            htmlfile.write(line)
64
65        jsonfile.write(json.dumps(versions_list, indent=4))
66
67        jsonfile.close()
68        template.close()
69        htmlfile.close()
70