1# Copyright 2015 Google Inc. All rights reserved. 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 16 17 18class _Bailout(Exception): 19 pass 20 21 22class ArgumentParser(argparse.ArgumentParser): 23 SUPPRESS = argparse.SUPPRESS 24 25 def __init__(self, host, prog, desc, **kwargs): 26 kwargs['prog'] = prog 27 kwargs['description'] = desc 28 kwargs['formatter_class'] = argparse.RawDescriptionHelpFormatter 29 super(ArgumentParser, self).__init__(**kwargs) 30 self._host = host 31 self.exit_status = None 32 self.add_argument('-V', '--version', action='store_true', 33 help='print the version and exit') 34 35 def parse_args(self, args=None, namespace=None): 36 try: 37 rargs = super(ArgumentParser, self).parse_args(args=args, 38 namespace=namespace) 39 except _Bailout: 40 return None 41 42 return rargs 43 44 # Redefining built-in 'file' pylint: disable=W0622 45 46 def _print_message(self, msg, file=None): 47 self._host.print_(msg=msg, stream=file, end='\n') 48 49 def print_help(self, file=None): 50 self._print_message(msg=self.format_help(), file=file) 51 52 def error(self, message, bailout=True): # pylint: disable=W0221 53 self.exit(2, '%s: error: %s\n' % (self.prog, message), bailout=bailout) 54 55 def exit(self, status=0, message=None, # pylint: disable=W0221 56 bailout=True): 57 self.exit_status = status 58 if message: 59 self._print_message(message, file=self._host.stderr) 60 if bailout: 61 raise _Bailout() 62