Esempio n. 1
0
class PluginConfig(object):
    """Represents configuation for each rhsm plugin.

    Attributes:
        plugin_conf_path: where plugin config files are found
        plugin_key: a string identifier for plugins, For ex, 'facts.FactsPlugin'
                    Used to find the configuration file.
    """
    plugin_key = None

    def __init__(self, plugin_key, plugin_conf_path=None):
        """init for PluginConfig.

        Args:
            plugin_key: string id for class
            plugin_conf_path: string file path to where plugin config files are found
        Raises:
            PluginConfigException: error when finding or loading plugin config
        """
        self.plugin_conf_path = plugin_conf_path
        self.plugin_key = plugin_key
        self.conf_files = []

        self.parser = SafeConfigParser()

        # no plugin_conf_path uses the default empty list of conf files
        if self.plugin_conf_path:
            self._get_config_file_path()

        try:
            self.parser.read(self.conf_files)
        except Exception, e:
            raise PluginConfigException(self.plugin_key, e)
Esempio n. 2
0
class PluginConfig(object):
    """Represents configuation for each rhsm plugin.

    Attributes:
        plugin_conf_path: where plugin config files are found
        plugin_key: a string identifier for plugins, For ex, 'facts.FactsPlugin'
                    Used to find the configuration file.
    """

    plugin_key = None

    def __init__(self, plugin_key, plugin_conf_path=None):
        """init for PluginConfig.

        Args:
            plugin_key: string id for class
            plugin_conf_path: string file path to where plugin config files are found
        Raises:
            PluginConfigException: error when finding or loading plugin config
        """
        self.plugin_conf_path = plugin_conf_path
        self.plugin_key = plugin_key
        self.conf_files = []

        self.parser = SafeConfigParser()

        # no plugin_conf_path uses the default empty list of conf files
        if self.plugin_conf_path:
            self._get_config_file_path()

        try:
            self.parser.read(self.conf_files)
        except Exception, e:
            raise PluginConfigException(self.plugin_key, e)
class TestBaseConduit(unittest.TestCase):
    def setUp(self):
        conf_string = StringIO("")
        self.conf = SafeConfigParser()
        self.conf.readfp(conf_string)
        self.conduit = plugins.BaseConduit(plugins.BaseConduit,
                                           self.conf)

    def test_default_boolean_false(self):
        val = self.conduit.conf_bool("main", "enabled", False)
        self.assertEquals(False, val)

    def test_default_boolean_true(self):
        val = self.conduit.conf_bool("main", "enabled", True)
        self.assertEquals(True, val)

    def test_bad_default_boolean(self):
        self.assertRaises(ValueError,
                          self.conduit.conf_bool,
                           "main", "enabled", "not a bool")

    def test_boolean_no_section(self):
        self.assertRaises(ValueError,
                          self.conduit.conf_bool,
                          'this_section_is_not_real', 'enabled')

    def test_default_int(self):
        val = self.conduit.conf_int("main", "enabled", 1)
        self.assertEquals(1, val)

    def test_bad_default_int(self):
        self.assertRaises(ValueError,
                          self.conduit.conf_int,
                          "main", "enabled", "not an int")

    def test_default_float(self):
        val = self.conduit.conf_float("main", "enabled", 1.0)
        self.assertEquals(1.0, val)

    def test_bad_default_float(self):
        self.assertRaises(ValueError,
                          self.conduit.conf_float,
                          "main", "enabled", "not a float")

    def test_default_string(self):
        val = self.conduit.conf_string("main", "enabled", "a string")
        self.assertEquals("a string", val)

    def test_string_no_section(self):
        val = self.conduit.conf_string('this_section_is_not_real', 'enabled')
        self.assertTrue(val is None)
Esempio n. 4
0
    def __generate(self):
        if not os.path.exists(self.repofile):
            return []

        # Unfortuantely, we can not use the SafeConfigParser for zypper repo
        # files because the repository urls contains strings which the
        # SafeConfigParser don't like. It would crash with
        # ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or '('
        if use_zypper:
            config = ConfigParser()
        else:
            config = SafeConfigParser()
        config.read(self.repofile)
        enabled_sections = [
            section for section in config.sections()
            if config.getboolean(section, "enabled")
        ]
        enabled_repos = []
        for section in enabled_sections:
            try:
                enabled_repos.append({
                    "repositoryid":
                    section,
                    "baseurl":
                    [self._format_baseurl(config.get(section, "baseurl"))]
                })
            except ImportError:
                break
        return enabled_repos
Esempio n. 5
0
 def reloadconf(self):
     if self.warnflush("load a new configuration"):
         return
     self._conf = SafeConfigParser()
     if len(self._paths) > 1:
         self._ui.status(_("\nSelect configuration to edit:\n"))
         for i in range(len(self._paths)):
             print " %s.  %s" % (str(i), self.pathclass(self._paths[i]))
         index = self._ui.promptchoice(
             self.getPrompt(), ["&" + str(num) for num in range(len(self._paths))], len(self._paths) - 1
         )
         self._path = self._paths[index]
     elif len(self._paths) == 1:
         self._path = self._paths[0]
     else:
         # This is a little silly, since without a valid config file
         # how could this extension be loaded? But for completeness...
         self._path = default = util.user_rcpath()[0]
         msg = _("Unable to find configuration file." " Would you like to make one at %s?") % default
         index = self._ui.promptchoice(msg, [_("&yes"), _("&no")], 0)
         if index == 1:
             self._ui.status(_("No configuration to edit"))
             sys.exit(0)
         open(default, "ab")
     self._conf.read((self._path))
     self._conf.data.clean_format()
     self._dirty = False
     self._ui.status(_("Configuration at '%s' loaded.\n") % self._path)
class TestBaseConduit(unittest.TestCase):
    def setUp(self):
        conf_string = StringIO("")
        self.conf = SafeConfigParser()
        self.conf.readfp(conf_string)
        self.conduit = plugins.BaseConduit(plugins.BaseConduit, self.conf)

    def test_default_boolean_false(self):
        val = self.conduit.conf_bool("main", "enabled", False)
        self.assertEquals(False, val)

    def test_default_boolean_true(self):
        val = self.conduit.conf_bool("main", "enabled", True)
        self.assertEquals(True, val)

    def test_bad_default_boolean(self):
        self.assertRaises(ValueError, self.conduit.conf_bool, "main",
                          "enabled", "not a bool")

    def test_boolean_no_section(self):
        self.assertRaises(ValueError, self.conduit.conf_bool,
                          'this_section_is_not_real', 'enabled')

    def test_default_int(self):
        val = self.conduit.conf_int("main", "enabled", 1)
        self.assertEquals(1, val)

    def test_bad_default_int(self):
        self.assertRaises(ValueError, self.conduit.conf_int, "main", "enabled",
                          "not an int")

    def test_default_float(self):
        val = self.conduit.conf_float("main", "enabled", 1.0)
        self.assertEquals(1.0, val)

    def test_bad_default_float(self):
        self.assertRaises(ValueError, self.conduit.conf_float, "main",
                          "enabled", "not a float")

    def test_default_string(self):
        val = self.conduit.conf_string("main", "enabled", "a string")
        self.assertEquals("a string", val)

    def test_string_no_section(self):
        val = self.conduit.conf_string('this_section_is_not_real', 'enabled')
        self.assertTrue(val is None)
Esempio n. 7
0
def setuser(ui, **opts):
    """
    Sets ui.username field in Mercurial configuration.
    Username saved in format: First Last <*****@*****.**>.
    If a -u option is passed, it overrides and
    username will be set to given string.

    Examples:

    hg setuser
    (Launches interactive editor to set username and password in default
     user configurationg file)

    hg setuser -n "Jerry Garcia" -e "*****@*****.**" -l
    (Sets username for the current local repository as
     'Jerry Garcia <*****@*****.**>')

    hg setuser -u "Paul Ringo John and George"
    (Sets default username to 'Paul Ringo John and George'.)
    """
    if opts["local"]:
        if not existslocalrepo():
            raise error.RepoLookupError(_("No local repository found"))
        path = repoconfpath()
    elif "HGRCPATH" in os.environ:
        path = os.environ["HGRCPATH"].split(os.pathsep)[0]
    else:
        path = util.user_rcpath()[0]
    if not os.path.exists(path):
        with open(path, "wb") as _empty:
            pass  # create empty file
    conf = SafeConfigParser()
    conf.read(path)
    if opts["username"]:
        username = opts["username"]
    else:
        if opts["name"]:
            name = opts["name"]
        else:
            name = ui.prompt(_("Full Name: "), "")
        if opts["email"]:
            email = opts["email"]
        else:
            email = ui.prompt(_("Email: "), "")
        email = " <%s>" % email if email else ""
        username = "******" % (name, email)
    if "ui" not in conf.sections():
        conf.add_section("ui")
    conf.set("ui", "username", username)
    savepretty(conf, path)
    ui.status(_("Username saved in %s\n") % path)
Esempio n. 8
0
    def __init__(self, plugin_key, plugin_conf_path=None):
        """init for PluginConfig.

        Args:
            plugin_key: string id for class
            plugin_conf_path: string file path to where plugin config files are found
        Raises:
            PluginConfigException: error when finding or loading plugin config
        """
        self.plugin_conf_path = plugin_conf_path
        self.plugin_key = plugin_key
        self.conf_files = []

        self.parser = SafeConfigParser()

        # no plugin_conf_path uses the default empty list of conf files
        if self.plugin_conf_path:
            self._get_config_file_path()

        try:
            self.parser.read(self.conf_files)
        except Exception, e:
            raise PluginConfigException(self.plugin_key, e)
Esempio n. 9
0
def get_home_currency():
    if Globals.HOME_CURRENCY is None:
        config = SafeConfigParser()
        config.read(Globals.INI_FILE)
        if config.has_section("defaults") and config.has_option(
                "defaults", "home_currency"):
            hc = config.get("defaults", "home_currency")
        else:
            hc = guess_home_currency()
            if hc:
                set_home_currency(hc)
        Globals.HOME_CURRENCY = hc
    return Globals.HOME_CURRENCY
Esempio n. 10
0
    def get(self, section, prop):
        """get a value from rhsm config

        Args:
            section: config file section
            prop: what config propery to find, he
                config item name
        Returns:
            The string value of the config item.
            If config item exists, but is not set,
            an empty string is return.
        """
        if not self.has_section(section):
            self.add_section(section)
        return SafeConfigParser.get(self, section, prop)
Esempio n. 11
0
    def get(self, section, prop):
        """get a value from rhsm config

        Args:
            section: config file section
            prop: what config propery to find, he
                config item name
        Returns:
            The string value of the config item.
            If config item exists, but is not set,
            an empty string is return.
        """
        if not self.has_section(section):
            self.add_section(section)
        return SafeConfigParser.get(self, section, prop)
Esempio n. 12
0
def setoption(ui, paths, optstring):
    """
    Sets option given in optstring in every path given in paths.
    Creates files, sections, and properties as needed.
    """
    match = re.search("^([\w\-<>]+)\.([\w\-<>\.]+)\s*=\s*(.*)", optstring)
    if not match:
        ui.warn(_("Invalid add property syntax. See 'hg help cedit'.\n"))
    else:
        sec = match.group(1)
        prop = match.group(2)
        val = match.group(3)
        for path in paths:
            conf = SafeConfigParser()
            conf.read(path)
            if sec not in conf.sections():
                conf.add_section(sec)
            conf.set(sec, prop, val)
            savepretty(conf, path)
            ui.status(_("Property set in %s\n") % path)
Esempio n. 13
0
    def __generate(self):
        if not os.path.exists(self.repofile):
            return []

        config = SafeConfigParser()
        config.read(self.repofile)
        enabled_sections = [section for section in config.sections() if config.getboolean(section, "enabled")]
        enabled_repos = []
        for section in enabled_sections:
            try:
                enabled_repos.append(
                    {
                        "repositoryid": section,
                        "baseurl": [self._replace_vars(config.get(section, "baseurl"))]
                    }
                )
            except ImportError:
                break
        return enabled_repos
Esempio n. 14
0
    def get(self, section, prop):
        """Get a value from rhsm config.

        :param section: config file section
        :type section: str
        :param prop: what config propery to find, the config item name
        :type prop: str
        :return: The string value of the config item.
        :rtype: str

        If config item exists, but is not set,
        an empty string is return.
        """
        try:
            return SafeConfigParser.get(self, section, prop)
        except InterpolationMissingOptionError:
            # if there is an interpolation error, resolve it
            raw_val = super(RhsmConfigParser, self).get(section, prop, True)
            interpolations = re.findall("%\((.*?)\)s", raw_val)
            changed = False
            for interp in interpolations:
                # Defaults aren't interpolated by default, so bake them in as necessary
                # has_option throws an exception if the section doesn't exist, but at this point we know it does
                if self.has_option(section, interp):
                    super(RhsmConfigParser,
                          self).set(section, interp, self.get(section, interp))
                    changed = True
            if changed:
                # Now that we have the required values, we can interpolate
                return self.get(section, prop)
            # If nothing has been changed (we couldn't fix it) re-raise the exception
            raise
        except (NoOptionError, NoSectionError) as er:
            try:
                return DEFAULTS[section][prop.lower()]
            except KeyError:
                # re-raise the NoOptionError, not the key error
                raise er
Esempio n. 15
0
    def __init__(self, plugin_key, plugin_conf_path=None):
        """init for PluginConfig.

        Args:
            plugin_key: string id for class
            plugin_conf_path: string file path to where plugin config files are found
        Raises:
            PluginConfigException: error when finding or loading plugin config
        """
        self.plugin_conf_path = plugin_conf_path
        self.plugin_key = plugin_key
        self.conf_files = []

        self.parser = SafeConfigParser()

        # no plugin_conf_path uses the default empty list of conf files
        if self.plugin_conf_path:
            self._get_config_file_path()

        try:
            self.parser.read(self.conf_files)
        except Exception, e:
            raise PluginConfigException(self.plugin_key, e)
Esempio n. 16
0
    def get(self, section, prop):
        """Get a value from rhsm config.

        :param section: config file section
        :type section: str
        :param prop: what config propery to find, the config item name
        :type prop: str
        :return: The string value of the config item.
        :rtype: str

        If config item exists, but is not set,
        an empty string is return.
        """
        try:
            return SafeConfigParser.get(self, section, prop)
        except InterpolationMissingOptionError:
            # if there is an interpolation error, resolve it
            raw_val = super(RhsmConfigParser, self).get(section, prop, True)
            interpolations = re.findall("%\((.*?)\)s", raw_val)
            changed = False
            for interp in interpolations:
                # Defaults aren't interpolated by default, so bake them in as necessary
                # has_option throws an exception if the section doesn't exist, but at this point we know it does
                if self.has_option(section, interp):
                    super(RhsmConfigParser, self).set(section, interp, self.get(section, interp))
                    changed = True
            if changed:
                # Now that we have the required values, we can interpolate
                return self.get(section, prop)
            # If nothing has been changed (we couldn't fix it) re-raise the exception
            raise
        except (NoOptionError, NoSectionError), er:
            try:
                return DEFAULTS[section][prop.lower()]
            except KeyError:
                # re-raise the NoOptionError, not the key error
                raise er
Esempio n. 17
0
    def __generate(self):
        if not os.path.exists(self.repofile):
            return []

        config = SafeConfigParser()
        config.read(self.repofile)
        enabled_sections = [section for section in config.sections() if config.getboolean(section, "enabled")]
        enabled_repos = []
        for section in enabled_sections:
            try:
                enabled_repos.append(
                    {
                        "repositoryid": section,
                        "baseurl": [self._replace_vars(config.get(section, "baseurl"))]
                    }
                )
            except ImportError:
                break
        return enabled_repos
Esempio n. 18
0
 def get(self, section, prop):
     if not self.has_section(section):
         self.add_section(section)
     return SafeConfigParser.get(self, section, prop)
Esempio n. 19
0
 def __init__(self, config_file=None, defaults=None):
     self.config_file = config_file
     SafeConfigParser.__init__(self)
     self.read(self.config_file)
Esempio n. 20
0
 def __init__(self, config_file=None, defaults=None):
     self.config_file = config_file
     SafeConfigParser.__init__(self)
     self.read(self.config_file)
Esempio n. 21
0
class hgconfig(object):
    """
    This class implements all of the logic for the interactive editor.
    """

    _opts = ["&add", "&delete", "&view", "re&load", "&write", "&quit", "&help"]
    _help = _(
        """
Mercurial configuration editor extension.

A '*' before the prompt denotes unsaved changes. See
http://www.selenic.com/mercurial/hgrc.5.html or 'man 5 hgrc'
for more information on configuration files.

Commands:
a       add to or modify your configuration
d       delete/remove a section or property from your configuration
v       view current configuration, including changes
w       write/save to file
q       quit
l       load a configuration from disk
h       view this help screen
"""
    )
    _dirty = False
    _ui = None
    _conf = None
    _path = ""
    _paths = []

    def __init__(self, ui):
        self._ui = ui
        self.setpaths()
        self.reloadconf()
        self.printhelp()
        while True:
            index = self._ui.promptchoice(self.getPrompt(), self._opts, len(self._opts) - 1)  # default to 'help'
            [
                self.modsection,
                self.delsection,
                self.viewconf,
                self.reloadconf,
                self.writeconf,
                self.exitext,
                self.printhelp,
            ][index]()

    def setpaths(self):
        paths = util.rcpath()
        paths.extend(util.os_rcpath())
        paths.append(repoconfpath())
        self._paths = verifypaths(paths)
        if existslocalrepo():
            self.checkpath(repoconfpath(), "repository")

    def checkpath(self, path, pathtype):
        if path not in self._paths and self._ui.promptchoice(
            _("No %s " + "configuration found. Would you like to create one (at %s) [y n]?") % (pathtype, path),
            ["&no", "&yes"],
            1,
        ):
            with open(path, "wb") as _empty:
                pass  # Create an empty file for later editing
            self._paths.append(path)

    def modsection(self):
        """Adds or modifies sections and properties to current configuration"""
        sec = self._ui.prompt(_("Enter section name: "), "")
        if sec not in self._conf.sections():
            self._conf.add_section(sec)
        prop = self._ui.prompt(_("Enter property name: "), "")
        try:
            old_val = _(" (currently '%s'): ") % self._conf.get(sec, prop)
        except NoOptionError:
            old_val = ": "
        val = self._ui.prompt(_("Enter property value %s") % old_val, "")
        self._conf.set(sec, prop, val)
        self._conf.data.clean_format()
        self._ui.status(_("Value set\n"))
        self._dirty = True

    def delsection(self):
        self._ui.status(_("Delete an entire (s)ection or a single (p)roperty" + " [(m) return to main menu]? \n"))
        index = self._ui.promptchoice(self.getPrompt(), ["&section", "&property", "&main"], 2)
        if index == 2:
            return
        elif index:
            sec = self._ui.prompt(_("Enter section name: "), "")
            prop = self._ui.prompt(_("Enter property name: "), "")
            try:
                if prop not in self._conf.options(sec):
                    self._ui.warn(_("Property '%s' not found\n") % prop)
                    return
                removed = self._conf.remove_option(sec, prop)
                if removed:
                    self._ui.status(_("Property removed\n"))
                    self._dirty = True
                else:
                    self._ui.warn(_("Unable to remove property '%s'\n") % prop)
            except NoSectionError:
                self._ui.warn(_("Section not found.\n"))
        else:
            sec = self._ui.prompt(_("Enter section name: "), "")
            if sec not in self._conf.sections():
                self._ui.warn(_("Section '%s' not found\n") % sec)
                return
            removed = self._conf.remove_section(sec)
            if removed:
                self._ui.status(_("Section removed\n"))
                self._dirty = True
            else:
                self._ui.warn(_("Unable to remove section '%s'\n") % sec)

    def viewconf(self):
        self._ui.status("(Location: %s)\n\n" % self._path)
        confstr = str(self._conf.data)
        if not confstr:
            self._ui.status(_("(Empty configuration)"))
        self._ui.status("%s\n" % confstr)

    def reloadconf(self):
        if self.warnflush("load a new configuration"):
            return
        self._conf = SafeConfigParser()
        if len(self._paths) > 1:
            self._ui.status(_("\nSelect configuration to edit:\n"))
            for i in range(len(self._paths)):
                print " %s.  %s" % (str(i), self.pathclass(self._paths[i]))
            index = self._ui.promptchoice(
                self.getPrompt(), ["&" + str(num) for num in range(len(self._paths))], len(self._paths) - 1
            )
            self._path = self._paths[index]
        elif len(self._paths) == 1:
            self._path = self._paths[0]
        else:
            # This is a little silly, since without a valid config file
            # how could this extension be loaded? But for completeness...
            self._path = default = util.user_rcpath()[0]
            msg = _("Unable to find configuration file." " Would you like to make one at %s?") % default
            index = self._ui.promptchoice(msg, [_("&yes"), _("&no")], 0)
            if index == 1:
                self._ui.status(_("No configuration to edit"))
                sys.exit(0)
            open(default, "ab")
        self._conf.read((self._path))
        self._conf.data.clean_format()
        self._dirty = False
        self._ui.status(_("Configuration at '%s' loaded.\n") % self._path)

    def writeconf(self):
        with open(self._path, "wb") as cfg:
            self._conf.write(cfg)
        self._ui.status(_("Configuration written to %s\n") % self._path)
        self._dirty = False

    def exitext(self):
        if self.warnflush("quit"):
            return
        sys.exit(0)

    def warnflush(self, action):
        return self._dirty and self._ui.promptchoice(
            "You have unsaved " "changes.\nReally %s before saving [y n]?" % action, ["&yes", "&no"], 1
        )

    def pathclass(self, path):
        pathtype = "[other]"
        if path == repoconfpath():
            pathtype = "[repository]"
        if path in util.user_rcpath():
            pathtype = "[user]"
        elif path in util.system_rcpath():
            pathtype = "[system-wide]"
        elif "HGRCPATH" in os.environ:
            if path in os.environ["HGRCPATH"].split(os.pathsep):
                pathtype = "[environment]"
        return "%s\t%s" % (path, pathtype)

    def printhelp(self):
        self._ui.status(self._help)

    def getPrompt(self):
        return "*>" if self._dirty else ">"
Esempio n. 22
0
class PluginConfig(object):
    """Represents configuation for each rhsm plugin.

    Attributes:
        plugin_conf_path: where plugin config files are found
        plugin_key: a string identifier for plugins, For ex, 'facts.FactsPlugin'
                    Used to find the configuration file.
    """
    plugin_key = None

    def __init__(self, plugin_key,
                 plugin_conf_path=None):
        """init for PluginConfig.

        Args:
            plugin_key: string id for class
            plugin_conf_path: string file path to where plugin config files are found
        Raises:
            PluginConfigException: error when finding or loading plugin config
        """
        self.plugin_conf_path = plugin_conf_path
        self.plugin_key = plugin_key
        self.conf_files = []

        self.parser = SafeConfigParser()

        # no plugin_conf_path uses the default empty list of conf files
        if self.plugin_conf_path:
            self._get_config_file_path()

        try:
            self.parser.read(self.conf_files)
        except Exception as e:
            raise PluginConfigException(self.plugin_key, e)

    def _get_config_file_path(self):
        conf_file = os.path.join(self.plugin_conf_path, self.plugin_key + ".conf")
        if not os.access(conf_file, os.R_OK):
            raise PluginConfigException(self.plugin_key, "Unable to find configuration file")
        # iniparse can handle a list of files, inc an empty list
        # reading an empty list is basically the None constructor
        self.conf_files.append(conf_file)

    def is_plugin_enabled(self):
        """returns True if the plugin is enabled in it's config."""
        try:
            enabled = self.parser.getboolean('main', 'enabled')
        except Exception as e:
            raise PluginConfigException(self.plugin_key, e)

        if not enabled:
            log.debug("Not loading \"%s\" plugin as it is disabled" % self.plugin_key)
            return False
        return True

    def __str__(self):
        buf = "plugin_key: %s\n" % (self.plugin_key)
        for conf_file in self.conf_files:
            buf = buf + "config file: %s\n" % conf_file
        # config file entries
        buf = buf + str(self.parser.data)
        return buf
Esempio n. 23
0
 def get(self, section, prop):
     if not self.has_section(section):
         self.add_section(section)
     return SafeConfigParser.get(self, section, prop)
Esempio n. 24
0
def getconfig(path):
    conf = SafeConfigParser()
    conf.read(path)
    if section not in conf.sections():
        conf.add_section(section)
    return conf
Esempio n. 25
0
def set_home_currency(curr):
    Globals.HOME_CURRENCY = curr
    config = SafeConfigParser()
    config.read(Globals.INI_FILE)
    if not config.has_section("defaults"):
        config.add_section("defaults")
    config.set("defaults", "home_currency", curr)
    if not os.path.isdir(os.path.dirname(Globals.INI_FILE)):
        os.makedirs(os.path.dirname(Globals.INI_FILE))
    with open(Globals.INI_FILE, "w") as fp:
        config.write(fp)
Esempio n. 26
0
 def __init__(self, config_string):
     SafeConfigParser.__init__(self)
     self.stringio = six.StringIO(config_string)
     self.readfp(self.stringio)
Esempio n. 27
0
 def setUp(self):
     conf_string = StringIO("")
     self.conf = SafeConfigParser()
     self.conf.readfp(conf_string)
     self.conduit = plugins.BaseConduit(plugins.BaseConduit, self.conf)
 def setUp(self):
     conf_string = StringIO("")
     self.conf = SafeConfigParser()
     self.conf.readfp(conf_string)
     self.conduit = plugins.BaseConduit(plugins.BaseConduit,
                                        self.conf)
Esempio n. 29
0
class PluginConfig(object):
    """Represents configuation for each rhsm plugin.

    Attributes:
        plugin_conf_path: where plugin config files are found
        plugin_key: a string identifier for plugins, For ex, 'facts.FactsPlugin'
                    Used to find the configuration file.
    """
    plugin_key = None

    def __init__(self, plugin_key,
                 plugin_conf_path=None):
        """init for PluginConfig.

        Args:
            plugin_key: string id for class
            plugin_conf_path: string file path to where plugin config files are found
        Raises:
            PluginConfigException: error when finding or loading plugin config
        """
        self.plugin_conf_path = plugin_conf_path
        self.plugin_key = plugin_key
        self.conf_files = []

        self.parser = SafeConfigParser()

        # no plugin_conf_path uses the default empty list of conf files
        if self.plugin_conf_path:
            self._get_config_file_path()

        try:
            self.parser.read(self.conf_files)
        except Exception as e:
            raise PluginConfigException(self.plugin_key, e)

    def _get_config_file_path(self):
        conf_file = os.path.join(self.plugin_conf_path, self.plugin_key + ".conf")
        if not os.access(conf_file, os.R_OK):
            raise PluginConfigException(self.plugin_key, "Unable to find configuration file")
        # iniparse can handle a list of files, inc an empty list
        # reading an empty list is basically the None constructor
        self.conf_files.append(conf_file)

    def is_plugin_enabled(self):
        """returns True if the plugin is enabled in it's config."""
        try:
            enabled = self.parser.getboolean('main', 'enabled')
        except Exception as e:
            raise PluginConfigException(self.plugin_key, e)

        if not enabled:
            log.debug("Not loading \"%s\" plugin as it is disabled" % self.plugin_key)
            return False
        return True

    def __str__(self):
        buf = "plugin_key: %s\n" % (self.plugin_key)
        for conf_file in self.conf_files:
            buf = buf + "config file: %s\n" % conf_file
        # config file entries
        buf = buf + str(self.parser.data)
        return buf
Esempio n. 30
0
def deleteoption(ui, paths, delstring):
    """
    Deletes property or section in delstring.
    To delete a section, the delstring should simply be the section name.
    To delete a property, the delstring should be the property qualified
    with the section, e.g. ui.username
    """
    secmatch = re.search("^\s*([\w\-<>]+)\s*$", delstring)
    propmatch = re.search("^\s*([\w\-<>]+)\.([\w\-<>\.]+)\s*$", delstring)
    if secmatch:
        sec = secmatch.group(1)
        for path in paths:
            conf = SafeConfigParser()
            conf.read(path)
            if sec not in conf.sections():
                ui.status(_("Success: No section '%s' in %s," + " so it's already gone.\n") % (sec, path))
            else:
                conf.remove_section(sec)
                savepretty(conf, path)
                ui.status(_("Section removed from %s\n") % path)
    elif propmatch:
        sec = propmatch.group(1)
        prop = propmatch.group(2)
        for path in paths:
            conf = SafeConfigParser()
            conf.read(path)
            if sec not in conf.sections():
                ui.status(_("Success: No section '%s' in %s, " + "so it's already gone.\n") % (sec, path))
            elif not conf.has_option(sec, prop):
                ui.status(_("Success: No property '%s' in %s, " + "so it's already gone.\n") % (prop, path))
            else:
                removed = conf.remove_option(sec, prop)
                if removed:
                    savepretty(conf, path)
                    ui.status(_("%s removed from %s\n") % (delstring, path))
                else:
                    ui.warn(_("Unable to remove %s from %s\n") % (delstring, path))
    else:
        ui.warn(_("Invalid delete syntax. See 'hg help cedit'.\n"))