Coverage for configman.value_sources.for_getopt: 92%

# Coverage for configman.value_sources.for_getopt : 92%

## 107 statements 98 run 9 missing 0 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is configman # # The Initial Developer of the Original Code is # Mozilla Foundation # Portions created by the Initial Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): # K Lars Lohn, lars@mozilla.com # Peter Bengtsson, peterbe@mozilla.com # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** """This module implements a configuration value source from the commandline. It uses getopt in its implementation. It is thought that this implementation will be supplanted by the argparse implementation when using Python 2.7 or greater. This module declares that its ValueSource constructor implementation can handle the getopt module or a list. If specified as the getopt module, the constructor will fetch the source of argv from the configmanager that was passed in. If specified as a list, the constructor will assume the list represents the argv source.""" import getopt import collections from .. import dotdict from .. import option from .. import namespace from ..config_exceptions import NotAnOptionError from .. import converters as conv from source_exceptions import ValueException, CantHandleTypeException class GetOptFailureException(ValueException): pass can_handle = (getopt, list, # a list of options to serve as the argv source ) class ValueSource(object): """The ValueSource implementation for the getopt module. This class will interpret an argv list of commandline arguments using getopt.""" def __init__(self, source, the_config_manager=None): if source is getopt: self.argv_source = the_config_manager.argv_source elif isinstance(source, collections.Sequence): self.argv_source = source else: raise CantHandleTypeException("don't know how to handle" " %s." % str(source)) def get_values(self, config_manager, ignore_mismatches): """This is the black sheep of the crowd of ValueSource implementations. It needs to know ahead of time all of the parameters that it will need, but we cannot give it. We may not know all the parameters because not all classes may have been expanded yet. The two parameters allow this ValueSource implementation to know what the parameters have already been defined. The 'ignore_mismatches' parameter tells the implementation if it can or cannot ignore extraneous commandline options. The last time this function is called, it will be required to test for illegal commandline options and respond accordingly.""" short_options_str, \ long_options_list = self.getopt_create_opts( config_manager.option_definitions) try: if ignore_mismatches: fn = ValueSource.getopt_with_ignore else: fn = getopt.gnu_getopt # here getopt looks through the command line arguments and # consumes the defined switches. The things that are not # consumed are then offered as the 'args' variable of the # parent configuration_manager getopt_options, config_manager.args = fn(self.argv_source, short_options_str, long_options_list) except getopt.GetoptError, x: raise NotAnOptionError(str(x)) command_line_values = dotdict.DotDict() for opt_name, opt_val in getopt_options: if opt_name.startswith('--'): name = opt_name[2:] else: name = self.find_name_with_short_form(opt_name[1:], config_manager.option_definitions, '') if not name: raise NotAnOptionError('%s is not a valid short' ' form option' % opt_name[1:]) option_ = config_manager._get_option(name) if option_.from_string_converter == conv.boolean_converter: command_line_values[name] = not option_.default else: command_line_values[name] = opt_val return command_line_values def getopt_create_opts(self, option_definitions): short_options_list = [] long_options_list = [] self.getopt_create_opts_recursive(option_definitions, "", short_options_list, long_options_list) short_options_str = ''.join(short_options_list) return short_options_str, long_options_list def getopt_create_opts_recursive(self, source, prefix, short_options_list, long_options_list): for key, val in source.items(): if isinstance(val, option.Option): boolean_option = type(val.default) == bool if val.short_form: try: if boolean_option: if val.short_form not in short_options_list: short_options_list.append(val.short_form) else: short_with_parameter = "%s:" % val.short_form if short_with_parameter not in short_options_list: short_options_list.append(short_with_parameter) except AttributeError: pass if boolean_option: long_options_list.append('%s%s' % (prefix, val.name)) else: long_options_list.append('%s%s=' % (prefix, val.name)) elif isinstance(val, option.Aggregation): pass # skip Aggregations they have nothing to do with getopt else: # Namespace case new_prefix = '%s%s.' % (prefix, key) self.getopt_create_opts_recursive(val, new_prefix, short_options_list, long_options_list) #-------------------------------------------------------------------------- @staticmethod def getopt_with_ignore(args, shortopts, longopts=[]): """my_getopt(args, options[, long_options]) -> opts, args This function works like gnu_getopt(), except that unknown parameters are ignored rather than raising an error. """ opts = [] prog_args = [] if isinstance(longopts, str): longopts = [longopts] else: longopts = list(longopts) while args: if args[0] == '--': prog_args += args[1:] break if args[0][:2] == '--': try: opts, args = getopt.do_longs(opts, args[0][2:], longopts, args[1:]) except getopt.GetoptError: prog_args.append(args[0]) args = args[1:] elif args[0][:1] == '-': try: opts, args = getopt.do_shorts(opts, args[0][1:], shortopts, args[1:]) except getopt.GetoptError: prog_args.append(args[0]) args = args[1:] else: prog_args.append(args[0]) args = args[1:] return opts, prog_args #-------------------------------------------------------------------------- def find_name_with_short_form(self, short_name, source, prefix): for key, val in source.items(): type_of_val = type(val) if type_of_val == namespace.Namespace: new_prefix = '%s.' % key name = self.find_name_with_short_form(short_name, val, new_prefix) if name: return name else: try: if short_name == val.short_form: return '%s%s' % (prefix, val.name) except KeyError: continue return None