1#!/usr/bin/env python 2# 3# Copyright 2017 - The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17"""gsi_util command-line utility.""" 18 19import argparse 20import logging 21import sys 22 23 24class GsiUtil(object): 25 """Object for gsi_util command line tool.""" 26 27 _GSI_UTIL_VERSION = '1.0' 28 29 # Adds gsi_util COMMAND here. 30 # TODO(bowgotsai): auto collect from gsi_util/commands/*.py 31 _COMMANDS = ['flash_gsi', 'pull', 'dump', 'check_compat'] 32 33 _LOGGING_FORMAT = '%(message)s' 34 _LOGGING_LEVEL = logging.WARNING 35 36 @staticmethod 37 def _get_module_name(command): 38 return 'gsi_util.commands.' + command 39 40 def run(self, argv): 41 """Command-line processor.""" 42 43 # Sets up default logging. 44 logging.basicConfig(format=self._LOGGING_FORMAT, level=self._LOGGING_LEVEL) 45 46 # Adds top-level --version/--debug argument. 47 parser = argparse.ArgumentParser() 48 parser.add_argument('-v', '--version', action='version', 49 version='%(prog)s {}'.format(self._GSI_UTIL_VERSION)) 50 parser.add_argument( 51 '-d', '--debug', help='debug mode.', action='store_true') 52 53 # Adds subparsers for each COMMAND. 54 subparsers = parser.add_subparsers(title='COMMAND') 55 for command in self._COMMANDS: 56 module_name = self._get_module_name(command) 57 mod = __import__(module_name, globals(), locals(), ['setup_command_args']) 58 mod.setup_command_args(subparsers) 59 60 args = parser.parse_args(argv[1:]) 61 if args.debug: 62 logging.getLogger().setLevel(logging.DEBUG) 63 64 try: 65 args.func(args) 66 except Exception as e: 67 logging.error('%s: %s', argv[0], e.message) 68 if args.debug: 69 logging.exception(e) 70 sys.exit(1) 71 72 73if __name__ == '__main__': 74 tool = GsiUtil() 75 tool.run(sys.argv) 76