Take Makefile improvements from anaconda.
[pykickstart.git] / pykickstart / options.py
blobe70ca38ee7ae2c2f7f0aad61d0011cc906628e62
2 # Chris Lumens <clumens@redhat.com>
4 # Copyright 2005, 2006, 2007 Red Hat, Inc.
6 # This copyrighted material is made available to anyone wishing to use, modify,
7 # copy, or redistribute it subject to the terms and conditions of the GNU
8 # General Public License v.2. This program is distributed in the hope that it
9 # will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
10 # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 # See the GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License along with
14 # this program; if not, write to the Free Software Foundation, Inc., 51
15 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
16 # trademarks that are incorporated in the source code or documentation are not
17 # subject to the GNU General Public License and may only be used or replicated
18 # with the express permission of Red Hat, Inc.
20 """
21 Specialized option handling.
23 This module exports two classes:
25 KSOptionParser - A specialized subclass of OptionParser to be used
26 in BaseHandler subclasses.
28 KSOption - A specialized subclass of Option.
29 """
30 import warnings
31 from copy import copy
32 from optparse import *
34 from constants import *
35 from errors import *
36 from version import *
38 from rhpl.translate import _
39 import rhpl.translate as translate
41 translate.textdomain("pykickstart")
43 class KSOptionParser(OptionParser):
44 """A specialized subclass of optparse.OptionParser to handle extra option
45 attribute checking, work error reporting into the KickstartParseError
46 framework, and to turn off the default help.
47 """
48 def exit(self, status=0, msg=None):
49 pass
51 def error(self, msg):
52 if self.lineno != None:
53 raise KickstartParseError, formatErrorMsg(self.lineno, msg=msg)
54 else:
55 raise KickstartParseError, msg
57 def keys(self):
58 retval = []
60 for opt in self.option_list:
61 if opt not in retval:
62 retval.append(opt.dest)
64 return retval
66 def _init_parsing_state (self):
67 OptionParser._init_parsing_state(self)
68 self.option_seen = {}
70 def check_values (self, values, args):
71 def seen(self, option):
72 return self.option_seen.has_key(option)
74 def usedTooNew(self, option):
75 return option.introduced and option.introduced > self.version
77 def usedDeprecated(self, option):
78 return option.deprecated
80 def usedRemoved(self, option):
81 return option.removed and option.removed <= self.version
83 for option in filter(lambda o: isinstance(o, Option), self.option_list):
84 if option.required and not seen(self, option):
85 raise KickstartValueError, formatErrorMsg(self.lineno, _("Option %s is required") % option)
86 elif seen(self, option) and usedTooNew(self, option):
87 mapping = {"option": option, "intro": versionToString(option.introduced),
88 "version": versionToString(self.version)}
89 self.error(_("The %(option)s option was introduced in version %(intro)s, but you are using kickstart syntax version %(version)s.") % mapping)
90 elif seen(self, option) and usedRemoved(self, option):
91 mapping = {"option": option, "removed": versionToString(option.removed),
92 "version": versionToString(self.version)}
94 if option.removed == self.version:
95 self.error(_("The %(option)s option is no longer supported.") % mapping)
96 else:
97 self.error(_("The %(option)s option was removed in version %(removed)s, but you are using kickstart syntax version %(version)s.") % mapping)
98 elif seen(self, option) and usedDeprecated(self, option):
99 mapping = {"lineno": self.lineno, "option": option}
100 warnings.warn(_("Ignoring deprecated option on line %(lineno)s: The %(option)s option has been deprecated and no longer has any effect. It may be removed from future releases, which will result in a fatal error from kickstart. Please modify your kickstart file to remove this option.") % mapping, DeprecationWarning)
102 return (values, args)
104 def __init__(self, map={}, lineno=None, version=None):
105 """Create a new KSOptionParser instance. Each KickstartCommand
106 subclass should create one instance of KSOptionParser, providing
107 at least the lineno attribute. map and version are not required.
108 Instance attributes:
110 map -- A mapping from option strings to different values.
111 lineno -- The line number of the line this KSOptionParser instance
112 is processing.
113 version -- The version of the kickstart syntax we are checking
114 against.
116 OptionParser.__init__(self, option_class=KSOption,
117 add_help_option=False,
118 conflict_handler="resolve")
119 self.map = map
120 self.lineno = lineno
121 self.version = version
123 # Creates a new Option class that supports several new attributes:
124 # - required: any option with this attribute must be supplied or an exception
125 # is thrown
126 # - introduced: the kickstart syntax version that this option first appeared
127 # in - an exception will be raised if the option is used and
128 # the specified syntax version is less than the value of this
129 # attribute
130 # - deprecated: the kickstart syntax version that this option was deprecated
131 # in - a DeprecationWarning will be thrown if the option is
132 # used and the specified syntax version is greater than the
133 # value of this attribute
134 # - removed: the kickstart syntax version that this option was removed in - an
135 # exception will be raised if the option is used and the specified
136 # syntax version is greated than the value of this attribute
137 # Also creates a new type:
138 # - ksboolean: support various kinds of boolean values on an option
139 # And two new actions:
140 # - map : allows you to define an opt -> val mapping such that dest gets val
141 # when opt is seen
142 # - map_extend: allows you to define an opt -> [val1, ... valn] mapping such
143 # that dest gets a list of vals built up when opt is seen
144 class KSOption (Option):
145 ATTRS = Option.ATTRS + ['introduced', 'deprecated', 'removed', 'required']
146 ACTIONS = Option.ACTIONS + ("map", "map_extend",)
147 STORE_ACTIONS = Option.STORE_ACTIONS + ("map", "map_extend",)
149 TYPES = Option.TYPES + ("ksboolean",)
150 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
152 def _check_required(self):
153 if self.required and not self.takes_value():
154 raise OptionError(_("Required flag set for option that doesn't take a value"), self)
156 def _check_ksboolean(option, opt, value):
157 if value.lower() in ("on", "yes", "true", "1"):
158 return True
159 elif value.lower() in ("off", "no", "false", "0"):
160 return False
161 else:
162 mapping = {"opt": opt, "value": value}
163 raise OptionValueError(_("Option %(opt)s: invalid boolean value: %(value)r") % mapping)
165 def _check_string(option, opt, value):
166 if len(value) > 2 and value.startswith("--"):
167 mapping = {"opt": opt, "value": value}
168 raise OptionValueError(_("Option %(opt)s: invalid string value: %(value)r") % mapping)
169 else:
170 return value
172 # Make sure _check_required() is called from the constructor!
173 CHECK_METHODS = Option.CHECK_METHODS + [_check_required]
174 TYPE_CHECKER.update({"ksboolean": _check_ksboolean, "string": _check_string})
176 def process (self, opt, value, values, parser):
177 Option.process(self, opt, value, values, parser)
178 parser.option_seen[self] = 1
180 # Override default take_action method to handle our custom actions.
181 def take_action(self, action, dest, opt, value, values, parser):
182 if action == "map":
183 values.ensure_value(dest, parser.map[opt.lstrip('-')])
184 elif action == "map_extend":
185 values.ensure_value(dest, []).extend(parser.map[opt.lstrip('-')])
186 else:
187 Option.take_action(self, action, dest, opt, value, values, parser)