1 # 2 # Copyright (C) 2018 The Android Open Source Project 3 # 4 # Licensed under the Apache License, Version 2.0 (the 'License'); 5 # you may not use this file except in compliance with the License. 6 # You may obtain a copy of the License at 7 # 8 # http://www.apache.org/licenses/LICENSE-2.0 9 # 10 # Unless required by applicable law or agreed to in writing, software 11 # distributed under the License is distributed on an 'AS IS' BASIS, 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 # See the License for the specific language governing permissions and 14 # limitations under the License. 15 # 16 17 import argparse 18 import logging 19 20 21 class ConsoleArgumentError(Exception): 22 """Raised when the console fails to parse commands.""" 23 pass 24 25 26 class ConsoleArgumentParser(argparse.ArgumentParser): 27 """The argument parser for a console command.""" 28 29 def __init__(self, command_name, description): 30 """Initializes the ArgumentParser without --help option. 31 32 Args: 33 command_name: A string, the first argument of the command. 34 description: The help message about the command. 35 """ 36 super(ConsoleArgumentParser, self).__init__( 37 prog=command_name, description=description, add_help=False) 38 39 def ParseLine(self, line): 40 """Parses a command line. 41 42 Args: 43 line: A string, the command line. 44 45 Returns: 46 An argparse.Namespace object. 47 """ 48 return self.parse_args(line.split()) 49 50 # @Override 51 def error(self, message): 52 """Raises an exception when failing to parse the command. 53 54 Args: 55 message: The error message. 56 57 Raises: 58 ConsoleArgumentError. 59 """ 60 raise ConsoleArgumentError(message)