2 # Chris Lumens <clumens@redhat.com>
4 # Copyright 2006, 2007, 2008 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.
21 Base classes for creating commands and syntax version object.
23 This module exports several important base classes:
25 BaseData - The base abstract class for all data objects. Data objects
26 are contained within a BaseHandler object.
28 BaseHandler - The base abstract class from which versioned kickstart
29 handler are derived. Subclasses of BaseHandler hold
30 BaseData and KickstartCommand objects.
32 DeprecatedCommand - An abstract subclass of KickstartCommand that should
33 be further subclassed by users of this module. When
34 a subclass is used, a warning message will be
37 KickstartCommand - The base abstract class for all kickstart commands.
38 Command objects are contained within a BaseHandler
41 from rhpl
.translate
import _
42 import rhpl
.translate
as translate
44 translate
.textdomain("pykickstart")
47 from pykickstart
.errors
import *
48 from pykickstart
.parser
import Packages
49 from pykickstart
.version
import versionToString
55 class KickstartCommand
:
56 """The base class for all kickstart commands. This is an abstract class."""
57 def __init__(self
, writePriority
=0):
58 """Create a new KickstartCommand instance. This method must be
59 provided by all subclasses, but subclasses must call
60 KickstartCommand.__init__ first. Instance attributes:
62 currentCmd -- The name of the command in the input file that
63 caused this handler to be run.
64 currentLine -- The current unprocessed line from the input file
65 that caused this handler to be run.
66 handler -- A reference to the BaseHandler subclass this
67 command is contained withing. This is needed to
68 allow referencing of Data objects.
69 lineno -- The current line number in the input file.
70 writePriority -- An integer specifying when this command should be
71 printed when iterating over all commands' __str__
72 methods. The higher the number, the later this
73 command will be written. All commands with the
74 same priority will be written alphabetically.
77 # We don't want people using this class by itself.
78 if self
.__class
__ is KickstartCommand
:
79 raise TypeError, "KickstartCommand is an abstract class."
81 self
.writePriority
= writePriority
83 # These will be set by the dispatcher.
89 def __call__(self
, *args
, **kwargs
):
90 """Set multiple attributes on a subclass of KickstartCommand at once
91 via keyword arguments. Valid attributes are anything specified in
92 a subclass, but unknown attributes will be ignored.
94 for (key
, val
) in kwargs
.items():
95 if hasattr(self
, key
):
96 setattr(self
, key
, val
)
99 """Return a string formatted for output to a kickstart file. This
100 method must be provided by all subclasses.
102 raise TypeError, "__str__() not implemented for KickstartCommand"
104 def parse(self
, args
):
105 """Parse the list of args and set data on the KickstartCommand object.
106 This method must be provided by all subclasses.
108 raise TypeError, "parse() not implemented for KickstartCommand"
110 # Set the contents of the opts object (an instance of optparse.Values
111 # returned by parse_args) as attributes on the KickstartCommand object.
112 # It's useful to call this from KickstartCommand subclasses after parsing
114 def _setToSelf(self
, optParser
, opts
):
115 for key
in filter (lambda k
: getattr(opts
, k
) != None, optParser
.keys()):
116 setattr(self
, key
, getattr(opts
, key
))
118 # Sets the contents of the opts object (an instance of optparse.Values
119 # returned by parse_args) as attributes on the provided object obj. It's
120 # useful to call this from KickstartCommand subclasses that handle lists
121 # of objects (like partitions, network devices, etc.) and need to populate
123 def _setToObj(self
, optParser
, opts
, obj
):
124 for key
in filter (lambda k
: getattr(opts
, k
) != None, optParser
.keys()):
125 setattr(obj
, key
, getattr(opts
, key
))
127 class DeprecatedCommand(KickstartCommand
):
128 """Specify that a command is deprecated and no longer has any function.
129 Any command that is deprecated should be subclassed from this class,
130 only specifying an __init__ method that calls the superclass's __init__.
131 This is an abstract class.
133 def __init__(self
, writePriority
=None):
134 # We don't want people using this class by itself.
135 if self
.__class
__ is KickstartCommand
:
136 raise TypeError, "DeprecatedCommand is an abstract class."
138 """Create a new DeprecatedCommand instance."""
139 KickstartCommand
.__init
__(self
, writePriority
)
142 """Placeholder since DeprecatedCommands don't work anymore."""
145 def parse(self
, args
):
146 """Print a warning message if the command is seen in the input file."""
147 mapping
= {"lineno": self
.lineno
, "cmd": self
.currentCmd
}
148 warnings
.warn(_("Ignoring deprecated command on line %(lineno)s: The %(cmd)s command 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 command.") % mapping
, DeprecationWarning)
155 """Each version of kickstart syntax is provided by a subclass of this
156 class. These subclasses are what users will interact with for parsing,
157 extracting data, and writing out kickstart files. This is an abstract
161 """version -- The version this syntax handler supports. This is set by
162 a class attribute of a BaseHandler subclass and is used to
163 set up the command dict. It is for read-only use.
167 def __init__(self
, mapping
={}):
168 """Create a new BaseHandler instance. This method must be provided by
169 all subclasses, but subclasses must call BaseHandler.__init__ first.
170 mapping is a custom map from command strings to classes, useful when
171 creating your own handler with special command objects. It is
172 otherwise unused and rarely needed.
176 commands -- A mapping from a string command to a KickstartCommand
177 subclass object that handles it. Multiple strings can
178 map to the same object, but only one instance of the
179 command object should ever exist. Most users should
180 never have to deal with this directly, as it is
181 manipulated internally and called through dispatcher.
182 currentLine -- The current unprocessed line from the input file
183 that caused this handler to be run.
184 packages -- An instance of pykickstart.parser.Packages which
185 describes the packages section of the input file.
186 platform -- A string describing the hardware platform, which is
187 needed only by system-config-kickstart.
188 scripts -- A list of pykickstart.parser.Script instances, which is
189 populated by KickstartParser.addScript and describes the
190 %pre/%post/%traceback script section of the input file.
193 # We don't want people using this class by itself.
194 if self
.__class
__ is BaseHandler
:
195 raise TypeError, "BaseHandler is an abstract class."
197 # This isn't really a good place for these, but it's better than
198 # everything else I can think of.
200 self
.packages
= Packages()
203 # These will be set by the dispatcher.
207 # A dict keyed by an integer priority number, with each value being a
208 # list of KickstartCommand subclasses. This dict is maintained by
209 # registerCommand and used in __str__. No one else should be touching
211 self
._writeOrder
= {}
213 self
._registerCommands
(mapping
=mapping
)
216 """Return a string formatted for output to a kickstart file."""
219 if self
.platform
!= "":
220 retval
+= "#platform=%s\n" % self
.platform
222 retval
+= "#version=%s\n" % versionToString(self
.version
)
224 lst
= self
._writeOrder
.keys()
228 for obj
in self
._writeOrder
[prio
]:
229 retval
+= obj
.__str
__()
231 for script
in self
.scripts
:
232 retval
+= script
.__str
__()
234 retval
+= self
.packages
.__str
__()
238 def _insertSorted(self
, list, obj
):
243 # If the two classes have the same name, it's because we are
244 # overriding an existing class with one from a later kickstart
245 # version, so remove the old one in favor of the new one.
246 if obj
.__class
__.__name
__ > list[i
].__class
__.__name
__:
248 elif obj
.__class
__.__name
__ == list[i
].__class
__.__name
__:
251 elif obj
.__class
__.__name
__ < list[i
].__class
__.__name
__:
259 def _setCommand(self
, cmdObj
):
260 # Add an attribute on this version object. We need this to provide a
261 # way for clients to access the command objects. We also need to strip
262 # off the version part from the front of the name.
263 if cmdObj
.__class
__.__name
__.find("_") != -1:
264 name
= unicode(cmdObj
.__class
__.__name
__.split("_", 1)[1])
266 name
= unicode(cmdObj
.__class
__.__name
__).lower()
268 setattr(self
, name
.lower(), cmdObj
)
270 # Also, add the object into the _writeOrder dict in the right place.
271 if cmdObj
.writePriority
is not None:
272 if self
._writeOrder
.has_key(cmdObj
.writePriority
):
273 self
._insertSorted
(self
._writeOrder
[cmdObj
.writePriority
], cmdObj
)
275 self
._writeOrder
[cmdObj
.writePriority
] = [cmdObj
]
277 def _registerCommands(self
, mapping
={}):
279 from pykickstart
.handlers
.control
import commandMap
, dataMap
280 cMap
= commandMap
[self
.version
]
281 dMap
= dataMap
[self
.version
]
283 from pykickstart
.handlers
.control
import dataMap
285 dMap
= dataMap
[self
.version
]
287 for (cmdName
, cmdClass
) in cMap
.iteritems():
288 # First make sure we haven't instantiated this command handler
289 # already. If we have, we just need to make another mapping to
290 # it in self.commands.
293 for (key
, val
) in self
.commands
.iteritems():
294 if val
.__class
__.__name
__ == cmdClass
.__name
__:
298 # If we didn't find an instance in self.commands, create one now.
301 self
._setCommand
(cmdObj
)
303 # Finally, add the mapping to the commands dict.
304 self
.commands
[cmdName
] = cmdObj
305 self
.commands
[cmdName
].handler
= self
307 # We also need to create attributes for the various data objects.
308 # No checks here because dMap is a bijection. At least, that's what
309 # the comment says. Hope no one screws that up.
310 for (dataName
, dataClass
) in dMap
.iteritems():
311 setattr(self
, dataName
, dataClass
)
313 def dispatcher(self
, args
, lineno
):
314 """Given a split up line of the input file and the current line number,
315 call the appropriate KickstartCommand handler that has been
316 previously registered. lineno is needed for error reporting. If
317 cmd does not exist in the commands dict, KickstartParseError will be
318 raised. A handler of None for the given command is not an error.
322 if not self
.commands
.has_key(cmd
):
323 raise KickstartParseError
, formatErrorMsg(lineno
, msg
=_("Unknown command: %s" % cmd
))
324 elif self
.commands
[cmd
] != None:
325 self
.commands
[cmd
].currentCmd
= cmd
326 self
.commands
[cmd
].currentLine
= self
.currentLine
327 self
.commands
[cmd
].lineno
= lineno
328 self
.commands
[cmd
].parse(args
[1:])
330 def maskAllExcept(self
, lst
):
331 """Set all entries in the commands dict to None, except the ones in
332 the lst. All other commands will not be processed.
334 self
._writeOrder
= {}
336 for (key
, val
) in self
.commands
.iteritems():
338 self
.commands
[key
] = None
340 def hasCommand(self
, cmd
):
341 """Return true if there is a handler for the string cmd."""
342 return hasattr(self
, cmd
)
349 """The base class for all data objects. This is an abstract class."""
351 """Create a new BaseData instance. There are no attributes."""
353 # We don't want people using this class by itself.
354 if self
.__class
__ is BaseData
:
355 raise TypeError, "BaseData is an abstract class."
358 """Return a string formatted for output to a kickstart file."""
361 def __call__(self
, *args
, **kwargs
):
362 """Set multiple attributes on a subclass of BaseData at once via
363 keyword arguments. Valid attributes are anything specified in a
364 subclass, but unknown attributes will be ignored.
366 for (key
, val
) in kwargs
.items():
367 if hasattr(self
, key
):
368 setattr(self
, key
, val
)