Sean McAllister | ebc7936 | 2020-11-20 14:28:08 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | # Copyright 2020 The Chromium OS Authors. All rights reserved. |
| 5 | # Use of this source code is governed by a BSD-style license that can be |
| 6 | # found in the LICENSE file. |
| 7 | """Aggregate one or more protobuffer messages into an output message. |
| 8 | |
| 9 | Takes a list of input messages and produces a single output message of some |
| 10 | aggregate type. If the message and aggregate types are the same, then |
| 11 | the following operation is performed, merging messages. Note that any repeated |
| 12 | fields are _concatenated_ not overwritten: |
| 13 | |
| 14 | output = OutputType() |
| 15 | for input in inputs: |
| 16 | output.MergeFrom(input) |
| 17 | |
| 18 | If the types are different, then the inputs are aggregated into the |
| 19 | values field of the output: |
| 20 | |
| 21 | output = OutputType() |
| 22 | for input in inputs: |
| 23 | output.values.append(input) |
| 24 | """ |
| 25 | |
| 26 | import argparse |
| 27 | |
| 28 | from checker import io_utils |
| 29 | from common import proto_utils |
| 30 | |
| 31 | if __name__ == '__main__': |
| 32 | parser = argparse.ArgumentParser( |
| 33 | description=__doc__, |
| 34 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 35 | ) |
| 36 | |
| 37 | parser.add_argument( |
| 38 | 'inputs', |
| 39 | type=str, |
| 40 | nargs='+', |
| 41 | help='message(s) to aggregate in jsonproto format', |
| 42 | ) |
| 43 | |
| 44 | parser.add_argument( |
| 45 | '-o', |
| 46 | '--output', |
| 47 | type=str, |
| 48 | required=True, |
| 49 | help='output file to write aggregated messages to', |
| 50 | ) |
| 51 | |
| 52 | # TODO: remove defaults once config_postsubmit change rolls out |
| 53 | parser.add_argument( |
| 54 | '-m', |
| 55 | '--message-type', |
| 56 | type=str, |
| 57 | default='chromiumos.config.payload.FlatConfigList', |
| 58 | help='input message type to aggregate', |
| 59 | ) |
| 60 | |
| 61 | parser.add_argument( |
| 62 | '-a', |
| 63 | '--aggregate-type', |
| 64 | type=str, |
| 65 | default='chromiumos.config.payload.FlatConfigList', |
| 66 | help='aggregage message type to output', |
| 67 | ) |
| 68 | |
| 69 | # load database of protobuffer name -> Type |
| 70 | protodb = proto_utils.create_symbol_db() |
| 71 | |
| 72 | options = parser.parse_args() |
| 73 | output = protodb.GetSymbol(options.aggregate_type)() |
| 74 | for path in options.inputs: |
| 75 | if options.message_type == options.aggregate_type: |
| 76 | output.MergeFrom( |
| 77 | io_utils.read_json_proto( |
| 78 | protodb.GetSymbol(options.message_type)(), path)) |
| 79 | else: |
| 80 | output.values.append( |
| 81 | io_utils.read_json_proto( |
| 82 | protodb.GetSymbol(options.message_type)(), path)) |
| 83 | |
| 84 | io_utils.write_message_json(output, options.output) |