コード例 #1
0
    def __init__(self,
                 mapping=None,
                 dataMapping=None,
                 commandUpdates=None,
                 dataUpdates=None,
                 *args,
                 **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartHandler.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # Any sections that we do not understand but want to prevent causing errors
        # are represented by a NullSection.  We want to preserve those on output, so
        # keep a list of their string representations here.  This is likely to change
        # in the future.  Don't rely on this exact implementation.
        self._null_section_strings = []

        self._registerCommands(mapping, dataMapping, commandUpdates,
                               dataUpdates)
コード例 #2
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.default = True
        pkgs.multiLib = True
        self.assertEqual("""%packages --default --multilib

%end""", str(pkgs).strip())
コード例 #3
0
    def runTest(self):
        pkgs = Packages()
        pkgs.default = True
        pkgs.multiLib = True
        self.assertEqual("""%packages --default --multilib

%end""",
                         str(pkgs).strip())
コード例 #4
0
ファイル: packages.py プロジェクト: atodorov/pykickstart
    def runTest(self):
        DevelPackagesBase.runTest(self)

        pkgs = Packages()
        pkgs.default = True
        pkgs.excludeWeakdeps = True
        self.assertEqual("""%packages --default --excludeWeakdeps

%end""", str(pkgs).strip())
コード例 #5
0
ファイル: packages.py プロジェクト: fepitre/pykickstart
    def runTest(self):
        DevelPackagesBase.runTest(self)

        pkgs = Packages()
        pkgs.default = True
        pkgs.excludeWeakdeps = True
        self.assertEqual("""%packages --default --excludeWeakdeps

%end""", str(pkgs).strip())
コード例 #6
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["-@Conflicts"])
        pkgs.add(["-@Clustering"])

        self.assertEqual("""%packages
-@Clustering
-@Conflicts

%end""", str(pkgs).strip())
コード例 #7
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["vim-*"])
        pkgs.add(["kde*"])

        self.assertEqual("""%packages
kde*
vim-*

%end""", str(pkgs).strip())
コード例 #8
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["@group-a"])
        pkgs.add(["@group-b"])
        pkgs.add(["-@group-a"])

        self.assertEqual("""%packages
@group-b
-@group-a

%end""", str(pkgs).strip())
コード例 #9
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["packageA"])
        pkgs.add(["packageB"])
        pkgs.add(["packageC"])

        self.assertEqual("""%packages
packageA
packageB
packageC

%end""", str(pkgs).strip())
コード例 #10
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["vim-enhanced"])
        pkgs.add(["package-b"])
        pkgs.add(["-vim-enhanced"])

        self.assertEqual("""%packages
package-b
-vim-enhanced

%end""",
                         str(pkgs).strip())
コード例 #11
0
ファイル: base.py プロジェクト: atodorov/pykickstart
    def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
                 dataUpdates=None, *args, **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartHandler.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # Any sections that we do not understand but want to prevent causing errors
        # are represented by a NullSection.  We want to preserve those on output, so
        # keep a list of their string representations here.  This is likely to change
        # in the future.  Don't rely on this exact implementation.
        self._null_section_strings = []

        self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)
コード例 #12
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["-enlightenment"])
        pkgs.add(["-clanlib"])
        pkgs.add(["-libass"])

        self.assertEqual("""%packages
-clanlib
-enlightenment
-libass

%end""",
                         str(pkgs).strip())
コード例 #13
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["-kde*"])
        pkgs.add(["-perl*"])
        pkgs.add(["-*spell"])

        self.assertEqual("""%packages
-*spell
-kde*
-perl*

%end""",
                         str(pkgs).strip())
コード例 #14
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["@^EnvironmentA"])
        pkgs.add(["@GroupB"])
        pkgs.add(["packageC"])

        self.assertEqual("""%packages
@^EnvironmentA
@GroupB
packageC

%end""",
                         str(pkgs).strip())
コード例 #15
0
ファイル: packages.py プロジェクト: fepitre/pykickstart
    def runTest(self):
        DevelPackagesBase.runTest(self)

        pkgs = Packages()
        pkgs.add(["vim-enhanced"])
        pkgs.add(["package-b"])
        pkgs.add(["-vim*"])

        self.assertEqual("""%packages
package-b
vim-enhanced
-vim*

%end""", str(pkgs).strip())
コード例 #16
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["vim-enhanced"])
        pkgs.add(["package-b"])
        pkgs.add(["-vim-enhanced"])

        self.assertEqual("""%packages
package-b
-vim-enhanced

%end""", str(pkgs).strip())
コード例 #17
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["-enlightenment"])
        pkgs.add(["-clanlib"])
        pkgs.add(["-libass"])

        self.assertEqual("""%packages
-clanlib
-enlightenment
-libass

%end""", str(pkgs).strip())
コード例 #18
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["-kde*"])
        pkgs.add(["-perl*"])
        pkgs.add(["-*spell"])

        self.assertEqual("""%packages
-*spell
-kde*
-perl*

%end""", str(pkgs).strip())
コード例 #19
0
ファイル: packages.py プロジェクト: KosiehBarter/pykickstart
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["@^EnvironmentA"])
        pkgs.add(["@GroupB"])
        pkgs.add(["packageC"])

        self.assertEqual("""%packages
@^EnvironmentA
@GroupB
packageC

%end""", str(pkgs).strip())
コード例 #20
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["vim-*"])
        pkgs.add(["kde*"])

        self.assertEqual("""%packages
kde*
vim-*

%end""", str(pkgs).strip())
コード例 #21
0
ファイル: packages.py プロジェクト: atodorov/pykickstart
    def runTest(self):
        DevelPackagesBase.runTest(self)

        pkgs = Packages()
        pkgs.add(["vim-enhanced"])
        pkgs.add(["package-b"])
        pkgs.add(["-vim*"])

        self.assertEqual("""%packages
package-b
vim-enhanced
-vim*

%end""", str(pkgs).strip())
コード例 #22
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["-@Conflicts"])
        pkgs.add(["-@Clustering"])

        self.assertEqual("""%packages
-@Clustering
-@Conflicts

%end""",
                         str(pkgs).strip())
コード例 #23
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["@group-a"])
        pkgs.add(["@group-b"])
        pkgs.add(["-@group-a"])

        self.assertEqual("""%packages
@group-b
-@group-a

%end""",
                         str(pkgs).strip())
コード例 #24
0
    def runTest(self):
        pkgs = Packages()
        pkgs.add(["packageA"])
        pkgs.add(["packageB"])
        pkgs.add(["packageC"])

        self.assertEqual("""%packages
packageA
packageB
packageC

%end""",
                         str(pkgs).strip())
コード例 #25
0
ファイル: packages.py プロジェクト: fepitre/pykickstart
    def runTest(self):
        DevelPackagesBase.runTest(self)

        pkgs = Packages()
        pkgs.add(["@GroupA"])
        pkgs.add(["@group-b"])
        pkgs.add(["@GroupC"])

        # Groups are printed out in alphabetic order, so group-b comes after Group*
        self.assertEqual("""%packages
@GroupA
@GroupC
@group-b

%end""", str(pkgs).strip())

        pkgs = Packages()
        pkgs.add(["@group-a --nodefaults"])
        self.assertEqual("""%packages
@group-a --nodefaults

%end""", str(pkgs).strip())

        pkgs = Packages()
        pkgs.add(["@group-a --optional"])
        self.assertEqual("""%packages
@group-a --optional

%end""", str(pkgs).strip())

        self.assertRaises(KickstartParseError, pkgs.add, ["@group-b --optional --nodefaults"])
コード例 #26
0
ファイル: base.py プロジェクト: M4rtinK/pykickstart
    def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
            dataUpdates=None, *args, **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           commands -- A mapping from a string command to a KickstartCommand
                       subclass object that handles it.  Multiple strings can
                       map to the same object, but only one instance of the
                       command object should ever exist.  Most users should
                       never have to deal with this directly, as it is
                       manipulated internally and called through dispatcher.
           currentLine -- The current unprocessed line from the input file
                          that caused this handler to be run.
           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartObject.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # These will be set by the dispatcher.
        self.commands = {}
        self.currentLine = ""

        # A dict keyed by an integer priority number, with each value being a
        # list of KickstartCommand subclasses.  This dict is maintained by
        # registerCommand and used in __str__.  No one else should be touching
        # it.
        self._writeOrder = {}

        self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)
コード例 #27
0
ファイル: base.py プロジェクト: M4rtinK/pykickstart
class BaseHandler(KickstartObject):
    """Each version of kickstart syntax is provided by a subclass of this
       class.  These subclasses are what users will interact with for parsing,
       extracting data, and writing out kickstart files.  This is an abstract
       class.

       version -- The version this syntax handler supports.  This is set by
                  a class attribute of a BaseHandler subclass and is used to
                  set up the command dict.  It is for read-only use.
    """
    version = None

    def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
            dataUpdates=None, *args, **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           commands -- A mapping from a string command to a KickstartCommand
                       subclass object that handles it.  Multiple strings can
                       map to the same object, but only one instance of the
                       command object should ever exist.  Most users should
                       never have to deal with this directly, as it is
                       manipulated internally and called through dispatcher.
           currentLine -- The current unprocessed line from the input file
                          that caused this handler to be run.
           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartObject.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # These will be set by the dispatcher.
        self.commands = {}
        self.currentLine = ""

        # A dict keyed by an integer priority number, with each value being a
        # list of KickstartCommand subclasses.  This dict is maintained by
        # registerCommand and used in __str__.  No one else should be touching
        # it.
        self._writeOrder = {}

        self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)

    def __str__(self):
        """Return a string formatted for output to a kickstart file."""
        retval = ""

        if self.platform != "":
            retval += "#platform=%s\n" % self.platform

        retval += "#version=%s\n" % versionToString(self.version)

        lst = list(self._writeOrder.keys())
        lst.sort()

        for prio in lst:
            for obj in self._writeOrder[prio]:
                obj_str = obj.__str__()
                if isinstance(obj_str, six.text_type) and not six.PY3:
                    obj_str = obj_str.encode("utf-8")
                retval += obj_str

        for script in self.scripts:
            script_str = script.__str__()
            if isinstance(script_str, six.text_type) and not six.PY3:
                script_str = script_str.encode("utf-8")
            retval += script_str

        retval += self.packages.__str__()

        return retval

    def _insertSorted(self, lst, obj):
        length = len(lst)
        i = 0

        while i < length:
            # If the two classes have the same name, it's because we are
            # overriding an existing class with one from a later kickstart
            # version, so remove the old one in favor of the new one.
            if obj.__class__.__name__ > lst[i].__class__.__name__:
                i += 1
            elif obj.__class__.__name__ == lst[i].__class__.__name__:
                lst[i] = obj
                return
            elif obj.__class__.__name__ < lst[i].__class__.__name__:
                break

        if i >= length:
            lst.append(obj)
        else:
            lst.insert(i, obj)

    def _setCommand(self, cmdObj):
        # Add an attribute on this version object.  We need this to provide a
        # way for clients to access the command objects.  We also need to strip
        # off the version part from the front of the name.
        if cmdObj.__class__.__name__.find("_") != -1:
            name = cmdObj.__class__.__name__.split("_", 1)[1]
            if not six.PY3:
                name = unicode(name)    # pylint: disable=undefined-variable
        else:
            name = cmdObj.__class__.__name__.lower()
            if not six.PY3:
                name = unicode(name)    # pylint: disable=undefined-variable

        setattr(self, name.lower(), cmdObj)

        # Also, add the object into the _writeOrder dict in the right place.
        if cmdObj.writePriority is not None:
            if cmdObj.writePriority in self._writeOrder:
                self._insertSorted(self._writeOrder[cmdObj.writePriority], cmdObj)
            else:
                self._writeOrder[cmdObj.writePriority] = [cmdObj]

    def _registerCommands(self, mapping=None, dataMapping=None, commandUpdates=None,
                          dataUpdates=None):
        if mapping == {} or mapping == None:
            from pykickstart.handlers.control import commandMap
            cMap = commandMap[self.version]
        else:
            cMap = mapping

        if dataMapping == {} or dataMapping == None:
            from pykickstart.handlers.control import dataMap
            dMap = dataMap[self.version]
        else:
            dMap = dataMapping

        if isinstance(commandUpdates, dict):
            cMap.update(commandUpdates)

        if isinstance(dataUpdates, dict):
            dMap.update(dataUpdates)

        for (cmdName, cmdClass) in list(cMap.items()):
            # First make sure we haven't instantiated this command handler
            # already.  If we have, we just need to make another mapping to
            # it in self.commands.
            # NOTE:  We can't use the resetCommand method here since that relies
            # upon cmdClass already being instantiated.  We'll just have to keep
            # these two code blocks in sync.
            cmdObj = None

            for (_key, val) in list(self.commands.items()):
                if val.__class__.__name__ == cmdClass.__name__:
                    cmdObj = val
                    break

            # If we didn't find an instance in self.commands, create one now.
            if cmdObj == None:
                cmdObj = cmdClass()
                self._setCommand(cmdObj)

            # Finally, add the mapping to the commands dict.
            self.commands[cmdName] = cmdObj
            self.commands[cmdName].handler = self

        # We also need to create attributes for the various data objects.
        # No checks here because dMap is a bijection.  At least, that's what
        # the comment says.  Hope no one screws that up.
        for (dataName, dataClass) in list(dMap.items()):
            setattr(self, dataName, dataClass)

    def resetCommand(self, cmdName):
        """Given the name of a command that's already been instantiated, create
           a new instance of it that will take the place of the existing
           instance.  This is equivalent to quickly blanking out all the
           attributes that were previously set.

           This method raises a KeyError if cmdName is invalid.
        """
        if cmdName not in self.commands:
            raise KeyError

        # mypy does not understand this, so ignore it for now
        cmdObj = self.commands[cmdName].__class__()

        self._setCommand(cmdObj)
        self.commands[cmdName] = cmdObj
        self.commands[cmdName].handler = self

    def dispatcher(self, args, lineno):
        """Call the appropriate KickstartCommand handler for the current line
           in the kickstart file.  A handler for the current command should
           be registered, though a handler of None is not an error.  Returns
           the data object returned by KickstartCommand.parse.

           args    -- A list of arguments to the current command
           lineno  -- The line number in the file, for error reporting
        """
        cmd = args[0]

        if cmd not in self.commands:
            raise KickstartParseError(formatErrorMsg(lineno, msg=_("Unknown command: %s") % cmd))
        elif self.commands[cmd] != None:
            self.commands[cmd].currentCmd = cmd
            self.commands[cmd].currentLine = self.currentLine
            self.commands[cmd].lineno = lineno
            self.commands[cmd].seen = True

            # The parser returns the data object that was modified.  This is either
            # the command handler object itself (a KickstartCommand object), or it's
            # a BaseData subclass instance that should be put into the command's
            # dataList.  The latter is done via side effects.
            #
            # Regardless, return the object that was given to us by the parser.
            obj = self.commands[cmd].parse(args[1:])

            # Here's the side effect part - don't worry about lst not being returned.
            lst = self.commands[cmd].dataList()
            if isinstance(obj, BaseData) and lst is not None:
                lst.append(obj)

            return obj

    def maskAllExcept(self, lst):
        """Set all entries in the commands dict to None, except the ones in
           the lst.  All other commands will not be processed.
        """
        self._writeOrder = {}

        for (key, _val) in list(self.commands.items()):
            if not key in lst:
                self.commands[key] = None

    def hasCommand(self, cmd):
        """Return true if there is a handler for the string cmd."""
        return hasattr(self, cmd)
コード例 #28
0
class BaseHandler(KickstartHandler):
    """A base kickstart handler.

       Each version of kickstart syntax is provided by a subclass of this
       class. These subclasses are what users will interact with for parsing,
       extracting data, and writing out kickstart files.  This is an abstract
       class.
    """
    def __init__(self,
                 mapping=None,
                 dataMapping=None,
                 commandUpdates=None,
                 dataUpdates=None,
                 *args,
                 **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartHandler.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # Any sections that we do not understand but want to prevent causing errors
        # are represented by a NullSection.  We want to preserve those on output, so
        # keep a list of their string representations here.  This is likely to change
        # in the future.  Don't rely on this exact implementation.
        self._null_section_strings = []

        self._registerCommands(mapping, dataMapping, commandUpdates,
                               dataUpdates)

    def __str__(self):
        """Return a string formatted for output to a kickstart file."""
        retval = "# Generated by pykickstart v%s\n" % __version__

        if self.platform:
            retval += "#platform=%s\n" % self.platform

        retval += "#version=%s\n" % versionToString(self.version)

        retval += KickstartHandler.__str__(self)

        for script in self.scripts:
            retval += script.__str__()

        if self._null_section_strings:
            retval += "\n"

            for s in self._null_section_strings:
                retval += s

        retval += self.packages.__str__()

        return retval

    def _registerCommands(self,
                          mapping=None,
                          dataMapping=None,
                          commandUpdates=None,
                          dataUpdates=None):
        if mapping == {} or mapping is None:
            from pykickstart.handlers.control import commandMap
            cMap = commandMap[self.version]
        else:
            cMap = mapping

        if dataMapping == {} or dataMapping is None:
            from pykickstart.handlers.control import dataMap
            dMap = dataMap[self.version]
        else:
            dMap = dataMapping

        # Apply the command and data updates, but do
        # not modify the original command and data maps.
        if isinstance(commandUpdates, dict):
            cMap = dict(cMap)
            cMap.update(commandUpdates)

        if isinstance(dataUpdates, dict):
            dMap = dict(dMap)
            dMap.update(dataUpdates)

        for (cmdName, cmdClass) in list(cMap.items()):
            self.registerCommand(cmdName, cmdClass)

        # No checks here because dMap is a bijection.  At least, that's what
        # the comment says.  Hope no one screws that up.
        for (dataName, dataClass) in list(dMap.items()):
            self.registerData(dataName, dataClass)

    def maskAllExcept(self, lst):
        """Set all entries in the commands dict to None, except the ones in
           the lst.  All other commands will not be processed.
        """
        self._writeOrder = {}

        for (key, _val) in list(self.commands.items()):
            if key not in lst:
                self.commands[key] = None

    def hasCommand(self, cmd):
        """Return true if there is a handler for the string cmd."""
        return hasattr(self, cmd)
コード例 #29
0
    def __init__(self,
                 mapping=None,
                 dataMapping=None,
                 commandUpdates=None,
                 dataUpdates=None,
                 *args,
                 **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           commands -- A mapping from a string command to a KickstartCommand
                       subclass object that handles it.  Multiple strings can
                       map to the same object, but only one instance of the
                       command object should ever exist.  Most users should
                       never have to deal with this directly, as it is
                       manipulated internally and called through dispatcher.
           currentLine -- The current unprocessed line from the input file
                          that caused this handler to be run.
           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartObject.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # These will be set by the dispatcher.
        self.commands = {}
        self.currentLine = ""

        # A dict keyed by an integer priority number, with each value being a
        # list of KickstartCommand subclasses.  This dict is maintained by
        # registerCommand and used in __str__.  No one else should be touching
        # it.
        self._writeOrder = {}

        self._registerCommands(mapping, dataMapping, commandUpdates,
                               dataUpdates)
コード例 #30
0
class BaseHandler(KickstartObject):
    """Each version of kickstart syntax is provided by a subclass of this
       class.  These subclasses are what users will interact with for parsing,
       extracting data, and writing out kickstart files.  This is an abstract
       class.

       version -- The version this syntax handler supports.  This is set by
                  a class attribute of a BaseHandler subclass and is used to
                  set up the command dict.  It is for read-only use.
    """
    version = None

    def __init__(self,
                 mapping=None,
                 dataMapping=None,
                 commandUpdates=None,
                 dataUpdates=None,
                 *args,
                 **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           commands -- A mapping from a string command to a KickstartCommand
                       subclass object that handles it.  Multiple strings can
                       map to the same object, but only one instance of the
                       command object should ever exist.  Most users should
                       never have to deal with this directly, as it is
                       manipulated internally and called through dispatcher.
           currentLine -- The current unprocessed line from the input file
                          that caused this handler to be run.
           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartObject.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # These will be set by the dispatcher.
        self.commands = {}
        self.currentLine = ""

        # A dict keyed by an integer priority number, with each value being a
        # list of KickstartCommand subclasses.  This dict is maintained by
        # registerCommand and used in __str__.  No one else should be touching
        # it.
        self._writeOrder = {}

        self._registerCommands(mapping, dataMapping, commandUpdates,
                               dataUpdates)

    def __str__(self):
        """Return a string formatted for output to a kickstart file."""
        retval = ""

        if self.platform:
            retval += "#platform=%s\n" % self.platform

        retval += "#version=%s\n" % versionToString(self.version)

        lst = list(self._writeOrder.keys())
        lst.sort()

        for prio in lst:
            for obj in self._writeOrder[prio]:
                obj_str = obj.__str__()
                if isinstance(obj_str, six.text_type) and not six.PY3:
                    obj_str = obj_str.encode("utf-8")
                retval += obj_str

        for script in self.scripts:
            script_str = script.__str__()
            if isinstance(script_str, six.text_type) and not six.PY3:
                script_str = script_str.encode("utf-8")
            retval += script_str

        retval += self.packages.__str__()

        return retval

    def _insertSorted(self, lst, obj):
        length = len(lst)
        i = 0

        while i < length:
            # If the two classes have the same name, it's because we are
            # overriding an existing class with one from a later kickstart
            # version, so remove the old one in favor of the new one.
            if obj.__class__.__name__ > lst[i].__class__.__name__:
                i += 1
            elif obj.__class__.__name__ == lst[i].__class__.__name__:
                lst[i] = obj
                return
            elif obj.__class__.__name__ < lst[i].__class__.__name__:
                break

        if i >= length:
            lst.append(obj)
        else:
            lst.insert(i, obj)

    def _setCommand(self, cmdObj):
        # Add an attribute on this version object.  We need this to provide a
        # way for clients to access the command objects.  We also need to strip
        # off the version part from the front of the name.
        if cmdObj.__class__.__name__.find("_") != -1:
            name = cmdObj.__class__.__name__.split("_", 1)[1]
            if not six.PY3:
                name = unicode(name)  # pylint: disable=undefined-variable
        else:
            name = cmdObj.__class__.__name__.lower()
            if not six.PY3:
                name = unicode(name)  # pylint: disable=undefined-variable

        setattr(self, name.lower(), cmdObj)

        # Also, add the object into the _writeOrder dict in the right place.
        if cmdObj.writePriority is not None:
            if cmdObj.writePriority in self._writeOrder:
                self._insertSorted(self._writeOrder[cmdObj.writePriority],
                                   cmdObj)
            else:
                self._writeOrder[cmdObj.writePriority] = [cmdObj]

    def _registerCommands(self,
                          mapping=None,
                          dataMapping=None,
                          commandUpdates=None,
                          dataUpdates=None):
        if mapping == {} or mapping is None:
            from pykickstart.handlers.control import commandMap
            cMap = commandMap[self.version]
        else:
            cMap = mapping

        if dataMapping == {} or dataMapping is None:
            from pykickstart.handlers.control import dataMap
            dMap = dataMap[self.version]
        else:
            dMap = dataMapping

        if isinstance(commandUpdates, dict):
            cMap.update(commandUpdates)

        if isinstance(dataUpdates, dict):
            dMap.update(dataUpdates)

        for (cmdName, cmdClass) in list(cMap.items()):
            # First make sure we haven't instantiated this command handler
            # already.  If we have, we just need to make another mapping to
            # it in self.commands.
            # NOTE:  We can't use the resetCommand method here since that relies
            # upon cmdClass already being instantiated.  We'll just have to keep
            # these two code blocks in sync.
            cmdObj = None

            for (_key, val) in list(self.commands.items()):
                if val.__class__.__name__ == cmdClass.__name__:
                    cmdObj = val
                    break

            # If we didn't find an instance in self.commands, create one now.
            if cmdObj is None:
                cmdObj = cmdClass()
                self._setCommand(cmdObj)

            # Finally, add the mapping to the commands dict.
            self.commands[cmdName] = cmdObj
            self.commands[cmdName].handler = self

        # We also need to create attributes for the various data objects.
        # No checks here because dMap is a bijection.  At least, that's what
        # the comment says.  Hope no one screws that up.
        for (dataName, dataClass) in list(dMap.items()):
            setattr(self, dataName, dataClass)

    def resetCommand(self, cmdName):
        """Given the name of a command that's already been instantiated, create
           a new instance of it that will take the place of the existing
           instance.  This is equivalent to quickly blanking out all the
           attributes that were previously set.

           This method raises a KeyError if cmdName is invalid.
        """
        if cmdName not in self.commands:
            raise KeyError

        cmdObj = self.commands[cmdName].__class__()

        self._setCommand(cmdObj)
        self.commands[cmdName] = cmdObj
        self.commands[cmdName].handler = self

    def dispatcher(self, args, lineno):
        """Call the appropriate KickstartCommand handler for the current line
           in the kickstart file.  A handler for the current command should
           be registered, though a handler of None is not an error.  Returns
           the data object returned by KickstartCommand.parse.

           args    -- A list of arguments to the current command
           lineno  -- The line number in the file, for error reporting
        """
        cmd = args[0]

        if cmd not in self.commands:
            raise KickstartParseError(
                formatErrorMsg(lineno, msg=_("Unknown command: %s") % cmd))
        elif self.commands[cmd] is not None:
            self.commands[cmd].currentCmd = cmd
            self.commands[cmd].currentLine = self.currentLine
            self.commands[cmd].lineno = lineno
            self.commands[cmd].seen = True

            # The parser returns the data object that was modified.  This is either
            # the command handler object itself (a KickstartCommand object), or it's
            # a BaseData subclass instance that should be put into the command's
            # dataList.  The latter is done via side effects.
            #
            # Regardless, return the object that was given to us by the parser.
            obj = self.commands[cmd].parse(args[1:])

            # Here's the side effect part - don't worry about lst not being returned.
            lst = self.commands[cmd].dataList()
            if isinstance(obj, BaseData) and lst is not None:
                lst.append(obj)

            return obj

    def maskAllExcept(self, lst):
        """Set all entries in the commands dict to None, except the ones in
           the lst.  All other commands will not be processed.
        """
        self._writeOrder = {}

        for (key, _val) in list(self.commands.items()):
            if key not in lst:
                self.commands[key] = None

    def hasCommand(self, cmd):
        """Return true if there is a handler for the string cmd."""
        return hasattr(self, cmd)
コード例 #31
0
ファイル: packages.py プロジェクト: atodorov/pykickstart
    def runTest(self):
        DevelPackagesBase.runTest(self)

        pkgs = Packages()
        pkgs.add(["@GroupA"])
        pkgs.add(["@group-b"])
        pkgs.add(["@GroupC"])

        # Groups are printed out in alphabetic order, so group-b comes after Group*
        self.assertEqual("""%packages
@GroupA
@GroupC
@group-b

%end""", str(pkgs).strip())

        pkgs = Packages()
        pkgs.add(["@group-a --nodefaults"])
        self.assertEqual("""%packages
@group-a --nodefaults

%end""", str(pkgs).strip())

        pkgs = Packages()
        pkgs.add(["@group-a --optional"])
        self.assertEqual("""%packages
@group-a --optional

%end""", str(pkgs).strip())

        self.assertRaises(KickstartParseError, pkgs.add, ["@group-b --optional --nodefaults"])
コード例 #32
0
ファイル: base.py プロジェクト: atodorov/pykickstart
class BaseHandler(KickstartHandler):
    """A base kickstart handler.

       Each version of kickstart syntax is provided by a subclass of this
       class. These subclasses are what users will interact with for parsing,
       extracting data, and writing out kickstart files.  This is an abstract
       class.
    """

    def __init__(self, mapping=None, dataMapping=None, commandUpdates=None,
                 dataUpdates=None, *args, **kwargs):
        """Create a new BaseHandler instance.  This method must be provided by
           all subclasses, but subclasses must call BaseHandler.__init__ first.

           mapping          -- A custom map from command strings to classes,
                               useful when creating your own handler with
                               special command objects.  It is otherwise unused
                               and rarely needed.  If you give this argument,
                               the mapping takes the place of the default one
                               and so must include all commands you want
                               recognized.
           dataMapping      -- This is the same as mapping, but for data
                               objects.  All the same comments apply.
           commandUpdates   -- This is similar to mapping, but does not take
                               the place of the defaults entirely.  Instead,
                               this mapping is applied after the defaults and
                               updates it with just the commands you want to
                               modify.
           dataUpdates      -- This is the same as commandUpdates, but for
                               data objects.


           Instance attributes:

           packages -- An instance of pykickstart.parser.Packages which
                       describes the packages section of the input file.
           platform -- A string describing the hardware platform, which is
                       needed only by system-config-kickstart.
           scripts  -- A list of pykickstart.parser.Script instances, which is
                       populated by KickstartParser.addScript and describes the
                       %pre/%pre-install/%post/%traceback script section of the
                       input file.
        """

        # We don't want people using this class by itself.
        if self.__class__ is BaseHandler:
            raise TypeError("BaseHandler is an abstract class.")

        KickstartHandler.__init__(self, *args, **kwargs)

        # This isn't really a good place for these, but it's better than
        # everything else I can think of.
        self.scripts = []
        self.packages = Packages()
        self.platform = ""

        # Any sections that we do not understand but want to prevent causing errors
        # are represented by a NullSection.  We want to preserve those on output, so
        # keep a list of their string representations here.  This is likely to change
        # in the future.  Don't rely on this exact implementation.
        self._null_section_strings = []

        self._registerCommands(mapping, dataMapping, commandUpdates, dataUpdates)

    def __str__(self):
        """Return a string formatted for output to a kickstart file."""
        retval = ""

        if self.platform:
            retval += "#platform=%s\n" % self.platform

        retval += "#version=%s\n" % versionToString(self.version)

        retval += KickstartHandler.__str__(self)

        for script in self.scripts:
            script_str = script.__str__()
            if isinstance(script_str, six.text_type) and not six.PY3:
                script_str = script_str.encode("utf-8")
            retval += script_str

        if self._null_section_strings:
            retval += "\n"

            for s in self._null_section_strings:
                retval += s

        retval += self.packages.__str__()

        return retval

    def _registerCommands(self, mapping=None, dataMapping=None, commandUpdates=None,
                          dataUpdates=None):
        if mapping == {} or mapping is None:
            from pykickstart.handlers.control import commandMap
            cMap = commandMap[self.version]
        else:
            cMap = mapping

        if dataMapping == {} or dataMapping is None:
            from pykickstart.handlers.control import dataMap
            dMap = dataMap[self.version]
        else:
            dMap = dataMapping

        # Apply the command and data updates, but do
        # not modify the original command and data maps.
        if isinstance(commandUpdates, dict):
            cMap = dict(cMap)
            cMap.update(commandUpdates)

        if isinstance(dataUpdates, dict):
            dMap = dict(dMap)
            dMap.update(dataUpdates)

        for (cmdName, cmdClass) in list(cMap.items()):
            self.registerCommand(cmdName, cmdClass)

        # No checks here because dMap is a bijection.  At least, that's what
        # the comment says.  Hope no one screws that up.
        for (dataName, dataClass) in list(dMap.items()):
            self.registerData(dataName, dataClass)

    def maskAllExcept(self, lst):
        """Set all entries in the commands dict to None, except the ones in
           the lst.  All other commands will not be processed.
        """
        self._writeOrder = {}

        for (key, _val) in list(self.commands.items()):
            if key not in lst:
                self.commands[key] = None

    def hasCommand(self, cmd):
        """Return true if there is a handler for the string cmd."""
        return hasattr(self, cmd)