1#!/usr/bin/env python3
2# SPDX-License-Identifier: BSD-3-Clause
3#
4# Copyright (c) 2022, Arm Limited. All rights reserved.
5
6"""
7Merge multiple json files in the order of the command line arguments.
8"""
9
10import argparse
11import json
12import os
13
14def update_relative_path(path, original_json_path, merged_json_path):
15    """
16    Update relative path according to its original and new base directory.
17    """
18    original_base_dir = os.path.dirname(original_json_path)
19    merged_base_dir = os.path.dirname(merged_json_path)
20
21    return os.path.relpath(original_base_dir + "/" + path, merged_base_dir)
22
23parser = argparse.ArgumentParser(
24    prog="merge_json",
25    description="Merge multiple JSON files into a single file.",
26    epilog="The merge happens in the order of command line arguments.")
27parser.add_argument("output", help="Output JSON file")
28parser.add_argument("inputs", nargs="+", help="Input JSON files")
29
30args = parser.parse_args()
31
32json_combined = {}
33
34for input_json_path in args.inputs:
35    print(f"Adding {input_json_path}")
36    with open(input_json_path, "rt", encoding="ascii") as f:
37        json_fragment = json.load(f)
38
39        # Align relative paths to merged JSON file's path
40        # The original JSON fragment and the merged JSON file might be placed
41        # in a different directory. This requires updating the relative paths
42        # in the JSON, so the merged file can have paths relative to itself.
43        keys = list(json_fragment.keys())
44        assert keys
45        sp = keys[0]
46
47        json_fragment[sp]["image"] = update_relative_path(
48            json_fragment[sp]["image"], input_json_path, args.output)
49        json_fragment[sp]["pm"] = update_relative_path(
50            json_fragment[sp]["pm"], input_json_path, args.output)
51
52        json_combined = {**json_combined, **json_fragment}
53
54with open(args.output, "wt", encoding="ascii") as f:
55    json.dump(json_combined, f, indent=4)
56