1# Copyright 2013 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4"""Module to hold the Command plugin.""" 5 6import argparse 7 8import cr 9 10 11class Command(cr.Plugin, cr.Plugin.Type): 12 """Base class for implementing cr commands. 13 14 These are the sub-commands on the command line, and modify the 15 accepted remaining arguments. 16 Commands in general do not implement the functionality directly, instead they 17 run a sequence of actions. 18 """ 19 20 @classmethod 21 def Select(cls): 22 """Called to select which command is active. 23 24 This picks a command based on the first non - argument on the command 25 line. 26 Returns: 27 the selected command, or None if not specified on the command line. 28 """ 29 if cr.context.args: 30 return getattr(cr.context.args, '_command', None) 31 return None 32 33 def __init__(self): 34 super(Command, self).__init__() 35 self.help = 'Missing help: {0}'.format(self.__class__.__name__) 36 self.description = None 37 self.epilog = None 38 self.parser = None 39 self.requires_build_dir = True 40 41 def AddArguments(self, subparsers): 42 """Add arguments to the command line parser. 43 44 Called by the main function to add the command to the command line parser. 45 Commands that override this function to add more arguments must invoke 46 this method. 47 Args: 48 subparsers: The argparse subparser manager to add this command to. 49 Returns: 50 the parser that was built for the command. 51 """ 52 self.parser = subparsers.add_parser( 53 self.name, 54 add_help=False, 55 help=self.help, 56 description=self.description or self.help, 57 epilog=self.epilog, 58 ) 59 self.parser.set_defaults(_command=self) 60 cr.context.AddCommonArguments(self.parser) 61 cr.base.client.AddArguments(self.parser) 62 return self.parser 63 64 def ConsumeArgs(self, parser, reason): 65 """Adds a remaining argument consumer to the parser. 66 67 A helper method that commands can use to consume all remaining arguments. 68 Use for things like lists of targets. 69 Args: 70 parser: The parser to consume remains for. 71 reason: The reason to give the user in the help text. 72 """ 73 parser.add_argument( 74 '_remains', metavar='arguments', 75 nargs=argparse.REMAINDER, 76 help='The additional arguments to {0}.'.format(reason) 77 ) 78 79 def EarlyArgProcessing(self): 80 """Called to make decisions based on speculative argument parsing. 81 82 When this method is called, enough of the command line parsing has been 83 done that the command is selected. This allows the command to make any 84 modifications needed before the final argument parsing is done. 85 """ 86 cr.base.client.ApplyOutArgument() 87 88 @cr.Plugin.activemethod 89 def Run(self): 90 """The main method of the command. 91 92 This is the only thing that a command has to implement, and it should not 93 call this base version. 94 """ 95 raise NotImplementedError('Must be overridden.') 96 97