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)
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)
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
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)
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
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)
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"))
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
def getconfig(path): conf = SafeConfigParser() conf.read(path) if section not in conf.sections(): conf.add_section(section) return conf
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(), ["§ion", "&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 ">"