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 15import argparse 16import sys 17 18import classpaths_pb2 19 20import google.protobuf.json_format as json_format 21import google.protobuf.text_format as text_format 22 23 24def encode(args): 25 pb = classpaths_pb2.ExportedClasspathsJars() 26 if args.format == 'json': 27 json_format.Parse(args.input.read(), pb) 28 else: 29 text_format.Parse(args.input.read(), pb) 30 args.output.write(pb.SerializeToString()) 31 args.input.close() 32 args.output.close() 33 34 35def decode(args): 36 pb = classpaths_pb2.ExportedClasspathsJars() 37 pb.ParseFromString(args.input.read()) 38 if args.format == 'json': 39 args.output.write(json_format.MessageToJson(pb)) 40 else: 41 args.output.write(text_format.MessageToString(pb).encode('utf_8')) 42 args.input.close() 43 args.output.close() 44 45 46def main(): 47 parser = argparse.ArgumentParser('Convert classpaths.proto messages between binary and ' 48 'human-readable formats.') 49 parser.add_argument('-f', '--format', default='textproto', 50 help='human-readable format, either json or text(proto), ' 51 'defaults to textproto') 52 parser.add_argument('-i', '--input', 53 nargs='?', type=argparse.FileType('rb'), default=sys.stdin.buffer) 54 parser.add_argument('-o', '--output', 55 nargs='?', type=argparse.FileType('wb'), 56 default=sys.stdout.buffer) 57 58 subparsers = parser.add_subparsers() 59 60 parser_encode = subparsers.add_parser('encode', 61 help='convert classpaths protobuf message from ' 62 'JSON to binary format', 63 parents=[parser], add_help=False) 64 65 parser_encode.set_defaults(func=encode) 66 67 parser_decode = subparsers.add_parser('decode', 68 help='print classpaths config in JSON format', 69 parents=[parser], add_help=False) 70 parser_decode.set_defaults(func=decode) 71 72 args = parser.parse_args() 73 args.func(args) 74 75 76if __name__ == '__main__': 77 main() 78