xref: /aosp_15_r20/external/pigweed/pw_bloat/py/pw_bloat/binary_size_aggregator.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2023 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""
15Collects binary size JSON outputs from bloat targets into a single file.
16"""
17
18import argparse
19import json
20import logging
21from pathlib import Path
22import sys
23
24
25import pw_cli.log
26
27_LOG = logging.getLogger(__package__)
28
29
30def _parse_args() -> argparse.Namespace:
31    """Parses the script's arguments."""
32
33    parser = argparse.ArgumentParser(__doc__)
34    parser.add_argument(
35        '--output',
36        type=Path,
37        required=True,
38        help='Output JSON file',
39    )
40    parser.add_argument(
41        'inputs',
42        type=Path,
43        nargs='+',
44        help='Input JSON files',
45    )
46
47    return parser.parse_args()
48
49
50def main(inputs: list[Path], output: Path) -> int:
51    all_data: dict[str, int] = {}
52
53    for file in inputs:
54        try:
55            all_data |= json.loads(file.read_text())
56        except FileNotFoundError:
57            target_name = file.name.split('.')[0]
58            _LOG.error('')
59            _LOG.error('JSON input file %s does not exist', file)
60            _LOG.error('')
61            _LOG.error(
62                'Check that the build target "%s" is a pw_size_report template',
63                target_name,
64            )
65            _LOG.error('')
66            return 1
67
68    output.write_text(json.dumps(all_data, sort_keys=True, indent=2))
69    return 0
70
71
72if __name__ == '__main__':
73    pw_cli.log.install()
74    sys.exit(main(**vars(_parse_args())))
75