blob: 1479d8cb9ae3739f0a5ee87f1144c73f77798f74 [file] [log] [blame]
Balint Dobszay9e2573d2022-08-10 15:15:21 +02001#!/usr/bin/env python3
2# SPDX-License-Identifier: BSD-3-Clause
3#
4# Copyright (c) 2022, Arm Limited. All rights reserved.
5
6"""
Imre Kisef22d442023-03-24 15:48:24 +01007Merge multiple json files in the order of the command line arguments.
Balint Dobszay9e2573d2022-08-10 15:15:21 +02008"""
9
Imre Kisef22d442023-03-24 15:48:24 +010010import argparse
Balint Dobszay9e2573d2022-08-10 15:15:21 +020011import json
Imre Kisef22d442023-03-24 15:48:24 +010012import os
Balint Dobszay9e2573d2022-08-10 15:15:21 +020013
Imre Kisef22d442023-03-24 15:48:24 +010014def 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)
Balint Dobszay9e2573d2022-08-10 15:15:21 +020020
Imre Kisef22d442023-03-24 15:48:24 +010021 return os.path.relpath(original_base_dir + "/" + path, merged_base_dir)
Balint Dobszay9e2573d2022-08-10 15:15:21 +020022
Imre Kisef22d442023-03-24 15:48:24 +010023parser = 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)