satayev | 075d07c | 2021-05-10 12:31:50 +0100 | [diff] [blame] | 1 | # Copyright (C) 2021 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://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, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | import argparse |
| 16 | |
| 17 | import classpaths_pb2 |
| 18 | |
| 19 | import google.protobuf.json_format as json_format |
| 20 | import google.protobuf.text_format as text_format |
| 21 | |
| 22 | |
| 23 | def encode(args): |
| 24 | pb = classpaths_pb2.ExportedClasspathsJars() |
| 25 | if args.format == 'json': |
| 26 | json_format.Parse(args.input.read(), pb) |
| 27 | else: |
| 28 | text_format.Parse(args.input.read(), pb) |
| 29 | args.output.write(pb.SerializeToString()) |
| 30 | args.input.close() |
| 31 | args.output.close() |
| 32 | |
| 33 | |
| 34 | def decode(args): |
| 35 | pb = classpaths_pb2.ExportedClasspathsJars() |
| 36 | pb.ParseFromString(args.input.read()) |
| 37 | if args.format == 'json': |
| 38 | args.output.write(json_format.MessageToJson(pb)) |
| 39 | else: |
| 40 | args.output.write(text_format.MessageToString(pb).encode('utf_8')) |
| 41 | args.input.close() |
| 42 | args.output.close() |
| 43 | |
| 44 | |
| 45 | def main(): |
| 46 | parser = argparse.ArgumentParser('Convert classpaths.proto messages between binary and ' |
| 47 | 'human-readable formats.') |
| 48 | parser.add_argument('-f', '--format', default='textproto', |
| 49 | help='human-readable format, either json or text(proto), ' |
| 50 | 'defaults to textproto') |
| 51 | parser.add_argument('-i', '--input', |
| 52 | nargs='?', type=argparse.FileType('rb'), default=sys.stdin.buffer) |
| 53 | parser.add_argument('-o', '--output', |
| 54 | nargs='?', type=argparse.FileType('wb'), |
| 55 | default=sys.stdout.buffer) |
| 56 | |
| 57 | subparsers = parser.add_subparsers() |
| 58 | |
| 59 | parser_encode = subparsers.add_parser('encode', |
| 60 | help='convert classpaths protobuf message from ' |
| 61 | 'JSON to binary format', |
| 62 | parents=[parser], add_help=False) |
| 63 | |
| 64 | parser_encode.set_defaults(func=encode) |
| 65 | |
| 66 | parser_decode = subparsers.add_parser('decode', |
| 67 | help='print classpaths config in JSON format', |
| 68 | parents=[parser], add_help=False) |
| 69 | parser_decode.set_defaults(func=decode) |
| 70 | |
| 71 | args = parser.parse_args() |
| 72 | args.func(args) |
| 73 | |
| 74 | |
| 75 | if __name__ == '__main__': |
| 76 | main() |