Example #1
0
def read_config_file(filename):
    """Return Settings instance built from contents of ``filename`` file."""
    parser = ConfigParser()
    parser.read(filename)
    settings = Settings()
    core_section = 'macman'
    default_section = 'default'
    # Handle core configuration.
    if parser.has_section(core_section):
        section = core_section
        for option in ['directory']:
            if parser.has_option(section, option):
                setattr(settings, option, parser.get(section, option))
    # Handle default configuration.
    if parser.has_section(default_section):
        section = settings.default
        settings.default = dict(parser.items(section))
    # Handle configuration of VMs.
    special_sections = (core_section, default_section)
    for section in parser.sections():
        if section in special_sections:
            continue
        vm_id = section
        settings.vms[vm_id] = dict(parser.items(section))
    return settings
Example #2
0
def readConfig(filename):
  hostname = os.path.basename(filename).split(".")[0]

  cp = ConfigParser()
  cp.readfp(open(filename))

  if cp.has_section("include"):
    includeFile = cp.get("include", "files")
    config = readConfig(includeFile)
  else:
    config = {}
  
  t = {}
  if hostname != 'common':
    t['hostname'] = hostname

  if cp.has_section("inet_http_server"):    
    port = cp.get("inet_http_server", "port")
    if port != None:
      t['port'] = port.split(":")[1]
    t['username'] = cp.get("inet_http_server", "username")
    t['password'] = cp.get("inet_http_server", "password")

  for k,v in t.items():
    if v != None:
      config[k] = v
  
  return config
class StoqdriversConfig:

    domain = 'stoqdrivers'

    def __init__(self, filename=None):
        """ filename is the name of the configuration file we're reading """

        self.filename = filename or (self.domain + '.conf')
        self.config = ConfigParser()
        self._load_config()

    def get_homepath(self):
        return os.path.join(os.getenv('HOME'), '.' + self.domain)

    def _open_config(self, path):
        filename = os.path.join(path, self.filename)
        if not os.path.exists(filename):
            return False
        self.config.read(filename)
        return True

    def _load_config(self):
        # Try to load configuration  from:
        # 1) $HOME/.$domain/$filename
        # 2) $PREFIX/etc/$domain/$filename
        # 3) /etc/$filename
        
        # This is a bit hackish:
        # $prefix / lib / $DOMAIN / lib / config.py
        #    -4      -3     -2      -1       0
        filename = os.path.abspath(__file__)
        stripped = filename.split(os.sep)[:-4]
        self.prefix = os.path.join(os.sep, *stripped)
        
        homepath = self.get_homepath()
        etcpath = os.path.join(self.prefix, 'etc', self.domain)
        globetcpath = os.path.join(os.sep, 'etc', self.domain)
        if not (self._open_config(homepath) or self._open_config(etcpath) or
                self._open_config(globetcpath)):
            raise ConfigError(_("Config file not found in: `%s', `%s' and "
                                "`%s'") % (homepath, etcpath, globetcpath))

    def has_section(self, section):
        return self.config.has_section(section)

    def has_option(self, name, section='General'):
        return self.config.has_option(section, name)
    
    def get_option(self, name, section='General'):
        if not self.config.has_section(section):
            raise  ConfigError(_("Invalid section: %s") % section)
        elif not self.config.has_option(section, name):
            raise ConfigError(_("%s does not have option: %s")
                              % (self.filename, name))
        return self.config.get(section, name)

    def set_option(self, name, section='General'):
        if not self.config.has_section(section):
            raise ConfigError(_("Invalid section: %s") % section)
        self.config.set(section, name)
Example #4
0
    def load_ini(self, ini_config):
        """
        Read the provided ini contents arguments and merge
        the data in the ini config into the config object.

        ini_config is assumed to be a string of the ini file contents.
        """
        parser = ConfigParser()
        parser.readfp(StringIO(ini_config))
        data = {
            'linters': {},
            'files': {},
            'branches': {},
        }
        if parser.has_section('files'):
            ignore = parser.get('files', 'ignore')
            data['files']['ignore'] = newline_value(ignore)
        if parser.has_section('branches'):
            ignore = parser.get('branches', 'ignore')
            data['branches']['ignore'] = comma_value(ignore)

        linters = []
        if parser.has_section('tools'):
            linters = comma_value(parser.get('tools', 'linters'))
        # Setup empty config sections
        for linter in linters:
            data['linters'][linter] = {}
        for section in parser.sections():
            if not section.startswith('tool_'):
                continue
            # Strip off tool_
            linter = section[5:]
            data['linters'][linter] = dict(parser.items(section))
        self.update(data)
def parseConfig(config_file):
    global num_cpus, num_l2

    print "\n==============================="
    print "Parsing gem5 config.ini file..."
    print config_file
    print "===============================\n"
    config = ConfigParser()
    if not config.read(config_file):
        print "ERROR: config file '", config_file, "' not found"
        sys.exit(1)

    if config.has_section("system.cpu"):
        num_cpus = 1
    else:
        num_cpus = 0
        while config.has_section("system.cpu" + str(num_cpus)):
            num_cpus += 1

    if config.has_section("system.l2"):
        num_l2 = 1
    else:
        num_l2 = 0
        while config.has_section("system.l2" + str(num_l2)):
            num_l2 += 1

    print "Num CPUs:", num_cpus
    print "Num L2s:", num_l2
    print ""

    return (num_cpus, num_l2)
Example #6
0
class Host(object):
    log=logging.getLogger('Pipeline')

    def __init__(self, config_file=None, hostname=None):
        self.config=ConfigParser()
        if not config_file:
            root_dir=os.path.abspath(os.path.join(os.path.dirname(__file__)))
            config_file=os.path.join(root_dir, 'config', 'hosts.conf')
            
        if not os.path.exists(config_file):
            raise RuntimeError('%s does not exist' % config_file)
        self.config.read(config_file)

        if hostname and not self.config.has_section(hostname):
            raise NoSectionError(hostname)
        elif not hostname: 
            for hn in [gethostname(), gethostname().split('.')[0]]:
                if self.config.has_section(hn):
                    self.hostname=hn
                    break
            try:
                self.hostname
            except AttributeError, e:
                hn=hostname if hostname else 'localhost (%s)' % gethostname()
                raise NoSectionError(hn)
        else:
Example #7
0
  def loadCfgFromFile(self):
    if not self.cfgFilePath or not path.exists(self.cfgFilePath):
      return

    cfg = ConfigParser()
    cfg.read(self.cfgFilePath)

    ## Iterate over both server and loader config sectoins as topAttr variable
    for cfgSection in cfgFileMap.keys(): 
      if not cfg.has_section(cfgSection):
        continue #FIXME: might want to raise error here... or warn

      ## This is now either self.server or self.loader depending on which key we are on
      topAttr = getattr(self, cfgSection)

      ## Let check the config file for a matchint config entry
      ## if we find it, set it and override any previous value
      for keyName in cfgFileMap[cfgSection].keys():
        if cfg.has_option(cfgSection, keyName):
          setattr(topAttr, keyName, cfg.get(cfgSection, keyName))
        else:
          print "Missing %s in section %s" % (keyName, cfgSection)
      

    ### Allow for static mapping of files to be configured
    if cfg.has_section('static_map'):
      for uriPath, dirPath in cfg.items('static_map'):
        self.staticMap[uriPath] = dirPath
    def parse_image_build_config(self, config_file_name):

        # Logic taken from koji.cli.koji.handle_image_build.
        # Unable to re-use koji's code because "cli" is not
        # a package of koji and this logic is intermingled
        # with CLI specific instructions.

        args = []
        opts = {}

        config = ConfigParser()
        config.readfp(self.get_default_image_build_conf())
        config.read(config_file_name)

        if self.architectures:
            config.set('image-build', 'arches', ','.join(self.architectures))
        elif self.architecture:
            config.set('image-build', 'arches', self.architecture)
        # else just use what was provided by the user in image-build.conf

        config_str = StringIO()
        config.write(config_str)
        self.log.debug('Image Build Config: \n%s', config_str.getvalue())

        image_name = None

        section = 'image-build'
        for option in ('name', 'version', 'arches', 'target', 'install_tree'):
            value = config.get(section, option)
            if not value:
                raise ValueError('{} cannot be empty'.format(option))
            if option == 'arches':
                value = [arch for arch in value.split(',') if arch]
            elif option == 'name':
                image_name = value
            args.append(value)
            config.remove_option(section, option)

        for option, value in config.items(section):
            if option in ('repo', 'format'):
                value = [v for v in value.split(',') if v]
            elif option in ('disk_size'):
                value = int(value)
            opts[option] = value

        section = 'ova-options'
        if config.has_section(section):
            ova = []
            for k, v in config.items(section):
                ova.append('{}={}'.format(k, v))
            opts['ova_option'] = ova

        section = 'factory-parameters'
        if config.has_section(section):
            factory = []
            for option, value in config.items(section):
                factory.append((option, value))
            opts['factory_parameter'] = factory

        return image_name, args, {'opts': opts}
	def searchConfig(self, nome):
		arquivo = ConfigParser()
		arquivo.read( self.arqRede )
		if arquivo.has_section( nome ):
			return {
					"ip"            : arquivo.get(nome,"ip"),
					"nome"          : nome,
					"prio"          : arquivo.get(nome,"prio"),
					"delimitado"    : arquivo.get(nome,"delimitado"),
					"isolado"       : arquivo.get(nome,"isolado"),
					"banda_down"    : arquivo.get(nome,"banda_down"),
					"banda_liberada": arquivo.get(nome,"banda_liberada"),
			}
		else:
			arquivo.read( self.arqMaquina )
		if arquivo.has_section( nome ):
			return {
					"ip"            : arquivo.get(nome,"ip"),
					"nome"          : nome,
					"prio"          : arquivo.get(nome,"prio"),
					"delimitado"    : arquivo.get(nome,"delimitado"),
					"isolado"       : arquivo.get(nome,"isolado"),
					"banda_down"    : arquivo.get(nome,"banda_down"),
					"banda_liberada": arquivo.get(nome,"banda_liberada"),
					"isolado"		: arquivo.get(nome,"isolado"),
					"delimitado"	: arquivo.get(nome,"delimitado"),
			}
Example #10
0
    def from_file(cls, file_name):
        """ Make a Config from a file. """
        file_name = os.path.expanduser(file_name)

        parser = ConfigParser()
        # IMPORTANT: Turn off downcasing of option names.
        parser.optionxform = str

        parser.read(file_name)
        cfg = Config()
        if parser.has_section('index_values'):
            for repo_id in parser.options('index_values'):
                cfg.version_table[repo_id] = (
                    parser.getint('index_values', repo_id))
        if parser.has_section('request_usks'):
            for repo_dir in parser.options('request_usks'):
                cfg.request_usks[repo_dir] = parser.get('request_usks',
                                                        repo_dir)
        if parser.has_section('insert_usks'):
            for repo_id in parser.options('insert_usks'):
                cfg.insert_usks[repo_id] = parser.get('insert_usks', repo_id)

        # ignored = fms_id|usk_hash|usk_hash|...
        if parser.has_section('fmsread_trust_map'):
            cfg.fmsread_trust_map.clear() # Wipe defaults.
            for ordinal in parser.options('fmsread_trust_map'):
                fields = parser.get('fmsread_trust_map',
                                    ordinal).strip().split('|')
                Config.validate_trust_map_entry(cfg, fields)
                cfg.fmsread_trust_map[fields[0]] = tuple(fields[1:])

        Config.update_defaults(parser, cfg)

        cfg.file_name = file_name
        return cfg
Example #11
0
 def test_fork(self):
     repo = HM.Repository(
         name='testrepo.hg',
         fs_path='/tmp/',
         url_path = '/test/',
         tool = 'hg',
         status = 'creating')
     repo_path = pkg_resources.resource_filename(
         'forgehg', 'tests/data/testrepo.hg')
     dirname = os.path.join(repo.fs_path, repo.name)
     if os.path.exists(dirname):
         shutil.rmtree(dirname)
     repo.init()
     repo._impl.clone_from(repo_path, copy_hooks=False)
     assert len(repo.log())
     assert not os.path.exists('/tmp/testrepo.hg/.hg/external-changegroup')
     assert not os.path.exists('/tmp/testrepo.hg/.hg/nested/nested-file')
     assert os.path.exists('/tmp/testrepo.hg/.hg/hgrc')
     cp = ConfigParser()
     cp.read('/tmp/testrepo.hg/.hg/hgrc')
     assert not cp.has_section('other')
     assert cp.has_section('hooks')
     assert not cp.has_option('hooks', 'changegroup.external')
     assert not cp.has_option('hooks', 'commit')
     self.assertEquals(cp.get('hooks', 'changegroup.sourceforge'), 'curl -s http://localhost//auth/refresh_repo/p/test/src-hg/')
     assert not os.path.exists('/tmp/testrepo.hg/.hg/undo.branch')
     shutil.rmtree(dirname)
Example #12
0
 def read(self, f):
     '''Read the settings from the given file handle.'''
     cfg = ConfigParser()
     cfg.readfp(f)
     
     netSection = 'Network'
     if cfg.has_section(netSection):
         if cfg.has_option(netSection, 'defaultIpAddress'):
             self.defaultIpAddress = cfg.get(netSection, 'defaultIpAddress')
         if cfg.has_option(netSection, 'defaultPort'):
             self.defaultPort = cfg.getint(netSection, 'defaultPort')
         if cfg.has_option(netSection, 'ephemeralPortsFrom'):
             self.ephemeralPorts[0] = cfg.getint(netSection, 'ephemeralPortsFrom')
         if cfg.has_option(netSection, 'ephemeralPortsTo'):
             self.ephemeralPorts[1] = cfg.getint(netSection, 'ephemeralPortsTo')
                     
     tftpSection = 'TFTP'
     if cfg.has_section(tftpSection):
         if cfg.has_option(tftpSection, 'timeout'):
             self.tftpTimeout = cfg.getfloat(tftpSection, 'timeout')
         if cfg.has_option(tftpSection, 'retries'):
             self.tftpRetries = cfg.getint(tftpSection, 'retries')
                     
     serverSection = 'Server'
     if cfg.has_section(serverSection):
         if cfg.has_option(serverSection, 'defaultDirectory'):
             self.defaultDirectory = cfg.get(serverSection, 'defaultDirectory')
         if cfg.has_option(serverSection, 'saveLastUsed'):
             self.saveLastUsed = cfg.getboolean(serverSection, 'saveLastUsed')
Example #13
0
def setup_config():
    cfg = ConfigParser(CFG_DEFAULTS)
    conf_file = J(WORK_DIR, 'checker.conf')
    cfg.read(conf_file)
    if not cfg.has_section('checker'):
        cfg.add_section('checker')
    if not cfg.has_section('mangos'):
        cfg.add_section('mangos')
    fp = open(conf_file, 'wt')
    cfg.write(fp)
    fp.close()
    return cfg
Example #14
0
 def readConfig(self):
     """ read some parameters from tokeidb.conf. The location of statdb.conf is defined in tokeidb.wsgi. """
     config = ConfigParser()
     files = config.read([os.environ['TOKEIDB_CONFIG_FILE']])
     params = {}
     if config.has_section('db'):
         params['dbhost'] = config.get('db', 'dbhost')
         params['appid'] = config.get('db', 'appid')
     if config.has_section('proxy'):
         params['pxhost'] = config.get('proxy', 'host')
         params['pxport'] = config.get('proxy', 'port')
     return params
Example #15
0
File: sim.py Project: ssm2017/pyosm
  def load(self):
    logging.main_logger.debug("[sim] 'load' called")

    # return if not a directory
    if not os.path.isdir(self.path):
      logging.main_logger.warning("[sim] sim %s not found" % (self.path))
      return False

    # check if there is a bin folder
    if os.path.isdir(self.path + '/bin'):
      self.has_bin_folder = True

    # check if there is an OpenSim.ini file
    if os.path.isfile(self.path + '/bin/OpenSim.exe'):
      self.has_opensim_exe = True

    # check if there is an OpenSim.ini file
    if os.path.isfile(self.path + '/bin/OpenSim.ini'):
      self.has_opensim_ini = True

    # check if there is an OpenSim.log file
    if os.path.isfile(self.path + '/log/OpenSim.log'):
      self.has_opensim_log = True

    # check if there is an OpenSim.log file
    if os.path.isfile(self.path + '/log/tmux.log'):
      self.has_tmux_log = True

    # check if there is a Regions.ini file
    if os.path.isfile(self.path + '/bin/Regions/Regions.ini'):
      self.has_regions_ini = True

    # check if RAdmin is enabled
    if self.has_opensim_ini:
      from ConfigParser import ConfigParser
      from helpers import sanitize
      opensim_ini = ConfigParser()
      opensim_ini.read(self.path + '/bin/OpenSim.ini')
      if opensim_ini.has_section('RemoteAdmin'):
        if opensim_ini.has_option('RemoteAdmin', 'enabled'):
          if opensim_ini.get('RemoteAdmin', 'enabled').lower() == 'true':
            if opensim_ini.has_option('RemoteAdmin', 'access_password'):
              self.radmin_password = sanitize(opensim_ini.get('RemoteAdmin', 'access_password'))
              self.radmin_ready = True
      if opensim_ini.has_section('Network'):
        if opensim_ini.has_option('Network', 'http_listener_port'):
          self.port = sanitize(opensim_ini.get('Network', 'http_listener_port'))
      if opensim_ini.has_section('Startup'):
        if opensim_ini.has_option('Startup', 'PIDFile'):
          self.pid_file = sanitize(opensim_ini.get('Startup', 'PIDFile')[1:-1])

    self.valid = self.has_bin_folder and self.pid_file != "" and self.has_opensim_exe and self.has_opensim_log and self.has_opensim_ini and self.has_regions_ini and self.has_tmux_log and self.radmin_ready
    return True
Example #16
0
class Config(object):

    def __init__(self):
        self._parser = ConfigParser()
        self._parser._defaults = IncludeDict(self._parser)

        # Copy attributes from the parser to avoid one additional
        # function call on each access.
        for attr in ["has_section", "remove_section"]:
            setattr(self, attr, getattr(self._parser, attr))

    def read_configs(self, configs):
        for config in configs:
            match = re.match("(.*)/([^/]+)=(.*)", config)
            if not match:
                raise Exception, "Invalid config string: %s" % config

            (name, option, value) = match.groups()
            if not self._parser.has_section(name):
                self._parser.add_section(name)

            self._parser.set(name, option, value)

    def read_file(self, file, filename="<stream>"):
        logging.info("Reading configurations from: %s", filename)

        self._parser.readfp(file, filename)

    def read_filename(self, filename):
        if not posixpath.exists(filename):
            raise Exception, "No such configuration file: %s" % filename

        file = open(filename, "r")
        return self.read_file(file, filename)

    def get_defaults(self):
        attributes = self._parser.defaults()
        return ConfigDefaults(self, 'DEFAULT', attributes)

    def get_section(self, name):
        if self._parser.has_section(name):
            attributes = dict(self._parser.items(name))
            return ConfigSection(self, name, attributes)

        return None

    def get_section_names(self):
        return self._parser.sections()

    def add_section(self, name):
        self._parser.add_section(name)
        return self.get_section(name)
Example #17
0
def migrate_ipbx(basedir):
	cfg = ConfigParser()
	cfg.read(basedir + '/ipbx.ini')

	if not cfg.has_section('configfiles'):
		cfg.add_section('configfiles')
	cfg.set('configfiles', 'path', '/etc/asterisk/extensions_extra.d')

	if not cfg.has_section('logaccess'):
		cfg.add_section('logaccess')
	cfg.set('logaccess'  , 'file', '/var/log/pf-xivo-web-interface/xivo.log')

	with open(basedir + '/ipbx.ini', 'wb') as fp:
		cfg.write(fp)
Example #18
0
def clean(start_page, end_page):
    """ Batch cleans the pages in text/clean."""

    config = ConfigParser()
    config.read('book.cnf')
    try:
        clean_headers = config.getboolean('process', 'clean_headers')
    except NoOptionError:
        clean_headers = True
    try:
        join_lines = config.getboolean('process', 'join_lines')
    except NoOptionError:
        join_lines = True

    if clean_headers:
	print 'cleaning headers'
        remove_headers()
        if not config.has_section('process'):
            config.add_section('process')
        config.set('process', 'clean_headers', 'false')
        with open('book.cnf', 'wb') as f:
            config.write(f)
        lm =_loaded_aspell_line_manager(start_page, end_page)
        lm.quick_fix()
    elif join_lines:
	print 'joining lines'
        if not config.has_section('process'):
            config.add_section('process')
        config.set('process', 'join_lines', 'false')
        with open('book.cnf', 'wb') as f:
            config.write(f)
        lm =_loaded_file_line_manager(start_page, end_page)
        lm.join_lines()
    else:
        # if interrupted by keyboard, go ahead and write changes
        lang = get_lang()
#           spell_checker.FileConfiguredSpellChecker(lang, './dict.{}.pws'.format(lang)),
#           spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        lm = line_manager.LineManager(
#           spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
            spell_checker.FileConfiguredSpellChecker(lang),
            start_page,
            end_page
            )
        lm.load('text/clean')
        try:
            lm.fix_lines()
        except KeyboardInterrupt:
            pass
    lm.write_pages('text/clean', False)
Example #19
0
 def parse(self):
     # extract project
     self.extract()
     # parse
     self._log.debug('Reading project info file...')
     prj_file = os.path.join(self._tmpdir, 'project_info')
     if os.path.exists(prj_file):
         cfg = ConfigParser()
         cfg.read(prj_file)
         if cfg.has_section('project'):
             self.id = cfg.get('project', 'id')
             self.name = cfg.get('project', 'name')
             self.author = cfg.get('project', 'author')
             self.aws_cert = cfg.get('project', 'aws_cert')
             self.aws_key = cfg.get('project', 'aws_key')
             self.aws_id = cfg.get('project', 'aws_id')
             self.aws_s3_bucket = cfg.get('project', 'aws_s3_bucket')
             self.aws_s3_access_id = cfg.get('project', 'aws_s3_access_id')
             self.aws_s3_access_key = cfg.get('project', 'aws_s3_access_key')
             self.version = cfg.get('project', 'version')
             self.distro = cfg.get('project', 'distro')
             self.environment = cfg.get('project', 'environment')
             self.project_type = cfg.get('project', 'project_type')
             self.arch = cfg.get('project', 'arch')
             self.distro_version = cfg.get('project', 'distro_version')
             self.src_iso = cfg.get('project', 'src_iso')
             if cfg.has_option('project', 'base_packages_removed'):
                 base_packages_removed = cfg.get('project', 'base_packages_removed')
                 self.base_packages_removed = base_packages_removed.split(',')
             if cfg.get('project', 'disk_image_type') != '':
                 self.disk_image_type = cfg.get('project', 'disk_image_type')
             if cfg.get('project', 'disk_image_size') != '':
                 self.disk_image_size = cfg.get('project', 'disk_image_size')
             self.output_file = cfg.get('project', 'output_file')
             if cfg.get('project', 'online').lower() == 'true':
                 self.online = True
             else:
                 self.online = False
             if cfg.get('project', 'run_post_config').lower() == 'true':
                 self.run_post_config = True
             else:
                 self.run_post_config = False
         if cfg.has_section('job'):
             self.job_id = cfg.get('job', 'id')
             self.job_status_post_url = cfg.get('job', 'post_url')
         # load packages
         return True
     else:
         self._log.error('Corrupt project.  Unable to load project info file.')
         return False
    def parse_image_build_config(self, config_file_name):

        # Logic taken from koji.cli.koji.handle_image_build.
        # Unable to re-use koji's code because "cli" is not
        # a package of koji and this logic is intermingled
        # with CLI specific instructions.

        args = []
        opts = {}

        config = ConfigParser()
        config.read(config_file_name)

        image_name = None

        section = 'image-build'
        for option in ('name', 'version', 'arches', 'target', 'install_tree'):
            value = config.get(section, option)
            if option == 'arches':
                value = [arch for arch in value.split(',') if arch]
            elif option == 'name':
                image_name = value
            args.append(value)
            config.remove_option(section, option)

        for option, value in config.items(section):
            if option in ('repo', 'format'):
                value = [v for v in value.split(',') if v]
            elif option in ('disk_size'):
                value = int(value)
            opts[option] = value

        section = 'ova-options'
        if config.has_section(section):
            ova = []
            for k, v in config.items(section):
                ova.append('{}={}'.format(k, v))
            opts['ova_option'] = ova

        section = 'factory-parameters'
        if config.has_section(section):
            factory = []
            for option, value in config.items(section):
                factory.append((option, value))
            opts['factory_parameter'] = factory

        # Set some defaults.
        opts.setdefault('disk_size', 10)

        return image_name, args, {'opts': opts}
Example #21
0
 def __init__(self):
     cfg = ConfigParser()
     try:
         cfg.read(globalcfgfile)
     except:
         pass
     if not cfg.has_section("userconfig"):
         self.loadlasttime = True
         self.openremote = True
         self.fontfamily = None
         self.fontsize = None
         self.__lastdir = home
         self.sengine_own = True
     if not cfg.has_section("searchext"):
         self.searchext = {"html": True, "htm": True, "js": False, "txt": False, "css": False}
     else:
         self.searchext = {}
         for a, b in cfg.items("searchext"):
             if b.lower() == "false":
                 self.searchext[a] = False
             else:
                 self.searchext[a] = True
     try:
         self.loadlasttime = cfg.getboolean("userconfig", "loadlasttime")
     except:
         self.lastlasttime = True
     try:
         self.sengine_own = cfg.getboolean("userconfig", "default_search_engine")
     except:
         self.sengine_own = True
     try:
         self.openremote = cfg.getboolean("userconfig", "openremote")
     except:
         self.openremote = True
     try:
         self.fontfamily = cfg.get("userconfig", "fontfamily").decode("utf-8")
         if self.fontfamily == "default":
             self.fontfamily = None
     except:
         self.fontfamily = None
     try:
         self.fontsize = cfg.getint("userconfig", "fontsize")
     except:
         self.fontsize = None
     try:
         self.__lastdir = cfg.get("userconfig", "lastdir")
     except:
         self.__lastdir = home
Example #22
0
  def readFrom(self, path, section):
    parser = ConfigParser()
    if not parser.read(path):
      raise CarbonConfigException("Failed to read config file %s" % path)

    if not parser.has_section(section):
      return

    for key, value in parser.items(section):
      key = key.upper()

      # Detect type from defaults dict
      if key in defaults:
        valueType = type(defaults[key])
      else:
        valueType = str

      if valueType is list:
        value = [v.strip() for v in value.split(',')]

      elif valueType is bool:
        value = parser.getboolean(section, key)

      else:
        # Attempt to figure out numeric types automatically
        try:
          value = int(value)
        except:
          try:
            value = float(value)
          except:
            pass

      self[key] = value
Example #23
0
class Config(object):
    def __new__(type, *args, **kwargs):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type)
        return type._the_instance
    
    def __init__(self, filename = None):
        if filename != None:
            self.filename = filename
            self.config = ConfigParser()
            self.config.read(self.filename)
    
    def get_section(self,name):
        if self.config.has_section(name):
            return _Section(name, self.config.items(name), self)
        else:
            return _Section(name, [], self)
    
    def __getattr__(self, attr):
        if attr == 'irc':
            return self.get_section('IRC')
        elif attr == 'ldap':
            return self.get_section('LDAP')
        elif attr == 'rpc':
            return self.get_section('RPC')
        elif attr == 'bot':
            return self.get_section('Bot')
        elif attr == 'smtp':
            return self.get_section('SMTP')
        elif attr == 'db':
            return self.get_section('Database')
        elif attr == 'identica':
            return self.get_section('Identi.ca')
        else:
            raise AttributeError('No section \'%s\' in Config.' % attr)
Example #24
0
class UserConfig:

    def __init__(self, filename=default_user_config_file):
        self.parser = ConfigParser()
        self.parser.read(filename)
        self.filename = filename
        if not isfile(self.filename):
            self.parser.add_section('diaspora')
            self.set_activated(False)
            self.__save()
        else:
            self.parser.read(self.filename)

        if not self.parser.has_section('diaspora'):
            self.parser.add_section('diaspora')

    def is_installed(self):
        return self.parser.getboolean('diaspora', 'activated')

    def set_activated(self, value):
        self.parser.set('diaspora', 'activated', str(value))
        self.__save()

    def __save(self):
        with open(self.filename, 'wb') as f:
            self.parser.write(f)
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
Example #26
0
def install_mercurial_hook():
    """
    Installs the mercurial precommit hook by adding a hook to the hgrc
    file in the .hg directory of the repository.
    """

    repo_dir = get_repo_dir()

    config_file = os.path.join(repo_dir, '.hg', 'hgrc')
    config_parser = ConfigParser()
    config_parser.read(config_file)

    precommit_abs_file = os.path.join(repo_dir, 'scripts',
            'codestyleprecommit.py')

    section = 'hooks'
    key = 'pretxncommit.precommit'
    value = 'python:%s:mercurial_hook' % precommit_abs_file

    if not config_parser.has_section(section):
        config_parser.add_section(section)

    config_parser.set(section, key, value)

    with open(config_file, 'w') as config:
        config_parser.write(config)
Example #27
0
class ConfigReader(object):
    """
    为傲世堂的游戏项目配置文件定制的配置读取类。
    陈超写的arg.gameOption耦合性太强,只能在bible内使用。
    但是配置文件的结构设计的很合理。

    此类就是根据原来的结构设计重新写的解耦并且适用性更广的类。

    Example::

        conf = ConfigReader(game, region)
        ip = conf.get("mobile_www_ip")
        if conf.has_option("mobile_www_port")
            port = conf.getint("mobile_www_port")     
    """
    def __init__(self, game, section, conf_dir='/app/opbin/work/bible/conf'):
        self.game = game
        self.section = section
        self.conf_file = '{}/{}.conf'.format(conf_dir.rstrip('/'), self.game)
        self.config = ConfigParser()
        self.config.read(self.conf_file)
        self.has_section = self.config.has_section(self.section)

    def has_option(self, option):
        return self._has_option(self.section, option) or self._has_option('common', option)

    def _has_option(self, section, option):
        return self.config.has_option(section, option)

    def get(self, option, raw=0, var=None):
        if self._has_option(self.section, option):
            return self.config.get(self.section, option, raw, var)
        elif self._has_option('common', option):
            return self.config.get('common', option, raw, var)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))

    def getint(self, option):
        if self._has_option(self.section, option):
            return self.config.getint(self.section, option)
        elif self._has_option('common', option):
            return self.config.getint('common', option)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))

    def getfloat(self, option):
        if self._has_option(self.section, option):
            return self.config.getfloat(self.section, option)
        elif self._has_option('common', option):
            return self.config.getfloat('common', option)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))

    def getboolean(self, option):
        if self._has_option(self.section, option):
            return self.config.getboolean(self.section, option)
        elif self._has_option('common', option):
            return self.config.getboolean('common', option)
        else:
            raise Exception("Can't find option: {} in {}".format(option, self.conf_file))
Example #28
0
def getVersionedFolderInfo(dirPath):
	"""
	returns a list containing the following information about the asset in dirPath:
	[0] last person to check it out, if locked
	[1] last person to check it in
	[2] time it was last checked in
	[3] latest comment on checkin
	[4] if it is isInstalled
	[5] filepath to install directory
	"""
	if not isVersionedFolder(dirPath):
		raise Exception("Not a versioned folder")
	
	nodeInfo = []
	cp = ConfigParser()
	cp.read(os.path.join(dirPath, ".nodeInfo"))
	if cp.getboolean("Versioning", "locked"):
		nodeInfo.append(cp.get("Versioning", "lastcheckoutuser"))
	else:
		nodeInfo.append("")
	nodeInfo.append(cp.get("Versioning", "lastcheckinuser"))
	nodeInfo.append(cp.get("Versioning", "lastcheckintime"))
	versionNum = int(cp.get("Versioning", "latestversion"))
	latestVersion = "v"+("%03d" % versionNum) 
	if cp.has_section("Comments"):
		nodeInfo.append(cp.get("Comments", latestVersion))
	else:
		nodeInfo.append('')
	if isInstalled(dirPath):
		nodeInfo.append("Yes")
		nodeInfo.append(glob.glob(os.path.join(dirPath, 'stable', '*stable*'))[0])
	else:
		nodeInfo.append("No")
		nodeInfo.append("")
	return nodeInfo
    def write_ini_config_file(self, command, data, client):
        """\
        Write the new command configuration in the plugin configuration file
        """
        try:

            # read the config file
            config = ConfigParser()
            config.read(command.plugin.config.fileName)

            # if there is no commands section
            if not config.has_section('commands'):
                raise NoSectionError('could not find <commands> section in '
                                     'plugin <%s> config file' % data['plugin_name'])

            # remove the old entry
            found = False
            for temp in config.options('commands'):
                search = temp.split('-')[0]
                if search == command.command:
                    config.remove_option('commands', temp)
                    found = True

            # set the new command option value
            config.set('commands', data['command_name'], data['command_level'])
            self.debug('%s command <%s> in plugin <%s> config file' % ('updated' if found else 'created new entry for',
                                                                       command.command, data['plugin_name']))

            # write the updated configuration file
            with open(command.plugin.config.fileName, 'wb') as configfile:
                config.write(configfile)

        except (IOError, NoSectionError), e:
            self.warning('could not change plugin <%s> config file: %s' % (data['plugin_name'], e))
            client.message('^7could not change plugin ^1%s ^7config file' % data['plugin_name'])
Example #30
0
    def __init__(self, config_filename):
        locale.setlocale(locale.LC_ALL, '')
        assert os.path.isfile(config_filename), "Config file not found"
        local_config_parser = ConfigParser()
        local_config_parser.read(config_filename)
        product_info_filename = local_config_parser.get("Config", "info_produtos")
        self._printer_name = local_config_parser.get("Config", "impressora")
        assert os.path.isfile(product_info_filename), "Product info file not found"
        # Set barcode filename
        self._barcode_filename = os.path.join(
            os.path.dirname(product_info_filename),
            "barcode"
        )

        cfg_parser = ConfigParser()
        cfg_parser.read(product_info_filename)

        self._primary_categories = dict(cfg_parser.items(self.PRIMARY_CATEGORY_SEC))
        self._secondary_categories = dict(cfg_parser.items(self.SECONDARY_CATEGORY_SEC))

        if cfg_parser.has_section(self.PRICE_SEC):
            self.price_list = []
            for opt in sorted(cfg_parser.options(self.PRICE_SEC)):
                self.price_list.append(cfg_parser.getfloat(self.PRICE_SEC, opt))
        else:
            self.price_list = [1.7, 2.21]
        
        self._label_header = cfg_parser.get("Label", "header").replace("\\n","\n")
        self._label_template = cfg_parser.get("Label", "label")
        self._labels_per_file = 30
        self._product_unity = "pç"
        self._category_on_label = cfg_parser.getint("Geral", "cat_etiqueta")