Convert a .ini file into a Node object.

    :param ini_file: a filename or a file like object in read mode
10931
def node_from_ini(ini_file, nodefactory=Node, root_name='ini'):
    
    fileobj = open(ini_file) if isinstance(ini_file, str) else ini_file
    cfp = configparser.RawConfigParser()
    cfp.read_file(fileobj)
    root = nodefactory(root_name)
    sections = cfp.sections()
    for section in sections:
        params = dict(cfp.items(section))
        root.append(Node(section, params))
    return root
404999
def _set_from_ini(self, namespace, ini_file):
        
        # Isolate global values
        global_vars = dict((key, val)
            for key, val in namespace.items()
            if isinstance(val, basestring)
        )

        # Copy all sections
        for section in ini_file.sections():
            # Get values set so far
            if section == "GLOBAL":
                raw_vars = global_vars
            else:
                raw_vars = namespace.setdefault(section.lower(), {})

            # Override with values set in this INI file
            raw_vars.update(dict(ini_file.items(section, raw=True)))

            # Interpolate and validate all values
            if section == "FORMATS":
                self._interpolation_escape(raw_vars)
            raw_vars.update(dict(
                (key, validate(key, val))
                for key, val in ini_file.items(section, vars=raw_vars)
            ))

        # Update global values
        namespace.update(global_vars)
372918
def parse(self, filename_or_file, initialize=True):
        
        if isinstance(filename_or_file, (str, unicode)):
            filename = filename_or_file
        else:
            filename = filename_or_file.name
        try:
            domtree = minidom.parse(filename_or_file)
        except xml.parsers.expat.ExpatError, e:
            args = [e.args[0]]
            if isinstance(filename, unicode):
                filename = filename.encode(sys.getdefaultencoding(), "replace")
            args.insert(0, '\n  File "%s"\n   ' % filename)
            raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
        if initialize:
            self.__init__()
        self.filename = filename
        self.load_dom(domtree, False)
932321
def get_config_file():
    # type: () -> AnyStr
    """"""
    parser = argparse.ArgumentParser(description="Read configuration file.")
    parser.add_argument('-ini', help="Full path of configuration file")
    args = parser.parse_args()
    ini_file = args.ini
    if not FileClass.is_file_exists(ini_file):
        print("Usage: -ini <full path to the configuration file.>")
        exit(-1)
    return ini_file
1247764
def _revert_tag_in_init(self):
        
        for line in fileinput.input(self.init_file, inplace=1):
            if line.strip().startswith("__version__"):
                line = "__version__ = \"" + self.init_version + "\""
            print(line.strip("\n"))
        
        print("reverted __init__.__version__ back to {}"
              .format(self.init_version))
202704
def _load_ini(self, namespace, config_file):
        
        self.LOG.debug("Loading %r..." % (config_file,))
        ini_file = ConfigParser.SafeConfigParser()
        ini_file.optionxform = str # case-sensitive option names
        if ini_file.read(config_file):
            self._set_from_ini(namespace, ini_file)
        else:
            self.LOG.warning("Configuration file %r not found,"
                             " use the command 'pyroadmin --create-config' to create it!" % (config_file,))
232350
def _decode(self, infile, encoding):
        
        if isinstance(infile, string_types):
            # can't be unicode
            # NOTE: Could raise a ``UnicodeDecodeError``
            return infile.decode(encoding).splitlines(True)
        for i, line in enumerate(infile):
            # NOTE: The isinstance test here handles mixed lists of unicode/string
            # NOTE: But the decode will break on any non-string values
            # NOTE: Or could raise a ``UnicodeDecodeError``
            if PY3K:
                if not isinstance(line, str):
                    infile[i] = line.decode(encoding)
            else:
                if not isinstance(line, unicode):
                    infile[i] = line.decode(encoding)
        return infile
882636
def init_node(cls, *args, **kwargs):
    
    node = cls()
    for name, value in zip(cls._fields, args):
        setattr(node, name, value)
    for name, value in kwargs:
        setattr(node, name, value)
    return node
134632
def to_ini
      string = @lines.to_a.map { |line| line.to_ini }.join($/)
      string = "#{ string }\n" unless string[-1] == "\n"

      string
    end
515523
def _read_ini_config(ini_file_contents: str) -> Dict[str, str]:
    
    config = configparser.ConfigParser()
    config.optionxform = str
    config.read_string(_FAKE_SECTION + ini_file_contents)

    items = {}
    for section in config.sections():
        items.update(dict(config[section].items()))

    return items
612081
def get_init(self, filename="__init__.py"):
        
        import ast

        with open(filename) as init_file:
            module = ast.parse(init_file.read())

        itr = lambda x: (ast.literal_eval(node.value) for node in ast.walk(module) \
            if isinstance(node, ast.Assign) and node.targets[0].id == x)

        try:
            return next(itr("__author__")), \
                   next(itr("__email__")), \
                   next(itr("__license__")), \
                   next(itr("__version__"))
        except StopIteration:
            raise ValueError("One of author, email, license, or version"
                        " cannot be found in {}".format(filename))
984501
def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
    -> InstanceNode:
    ''''''
    return InstanceNode(instance, xml_node, node_globals)
174545
def convert_ini(config_dict):
    
    config_lines = []

    for env, configs in sorted(config_dict.items()):
        for resource, app_properties in sorted(configs.items()):
            try:
                for app_property, value in sorted(app_properties.items()):
                    variable = '{env}_{resource}_{app_property}'.format(
                        env=env, resource=resource, app_property=app_property).upper()

                    if isinstance(value, (dict, DeepChainMap)):
                        safe_value = "'{0}'".format(json.dumps(dict(value)))
                    else:
                        safe_value = json.dumps(value)

                    line = "{variable}={value}".format(variable=variable, value=safe_value)

                    LOG.debug('INI line: %s', line)
                    config_lines.append(line)
            except AttributeError:
                resource = resource.upper()
                app_properties = "'{}'".format(json.dumps(app_properties))
                line = '{0}={1}'.format(resource, app_properties)

                LOG.debug('INI line: %s', line)
                config_lines.append(line)
    return config_lines
50683
private function _parseIni($iniFile)
    {
        $aParsedIni = parse_ini_file($iniFile, true, INI_SCANNER_RAW);
        $tmpArray = array();
        foreach ($aParsedIni as $key=>$value) {
            if (strpos($key, ':') !== false) {
                $sections = explode(':', $key);
                if (count($sections) != 2) {
                    throw new Exception('Malformed section header!');
                }
                $currentSection = trim($sections[0]);
                $parentSection = trim($sections[1]);
                $value = array_merge_recursive(
                    $aParsedIni[$parentSection],
                    $aParsedIni[$key]
                );
                $aParsedIni[$currentSection] = $value;
                unset($aParsedIni[$key]);
                $key = $currentSection;
            }
            if (is_array($value)) {
                foreach ($value as $vk=>$vv) {
                    $newKey = $key.".".$vk;
                    $tmpArray[$newKey] = $vv;
                    if (
                           is_string($vv) &&
                           preg_match_all('/\${([a-zA-Z0-9\.]+)}/', $vv, $match)
                        ) {
                        if (!isset($match[1])) {
                            continue;
                        }
                        $variableKey = $match[1];
                        foreach ($variableKey as &$var) {
                            if (strpos($var, '.') === false) {
                                $var = $key . '.' . $var;
                            }
                        }
                        $this->_varDeps[$newKey] = $variableKey;
                    }
                }
            }
        }
        if (!empty($tmpArray)) {
            $aParsedIni = $tmpArray;
        }
        foreach ($aParsedIni as $key=>$value) {    //extract parsed array keys
            if (array_key_exists($key, $this->_varDeps)) {
                $deps = &$this->_varDeps;
                $value = preg_replace_callback(
                    '/\${([a-zA-Z0-9\.]+)}/',
                    function ($match) use ($key, $aParsedIni, &$deps) {
                        return $aParsedIni[array_shift($deps[$key])];
                    },
                    $value
                );
                $aParsedIni[$key] = $value;
            }
            $this->_tmpValue = $value;//set temporay value to current ini value
            $aXKey = explode($this->_delimiter, $key);    //get ini key segments
            //set object properties recursively based on parsed ini
            $this->_recursiveInit($this->_obj, $aXKey);
        }
    }
1009433
def get_ini(self, incl_unset=False):
        

        configp = configparser.ConfigParser(allow_no_value=True)
        configp.read_dict(self._config)
        with StringIO() as config_ini:
            if self._parser:
                self._parser.set_defaults(
                    **self.get_section(self.root_section)
                )
                argparse_ini = argparse_to_ini(
                    parser=self._parser, incl_unset=incl_unset
                )
                return argparse_ini
            else:
                configp.write(config_ini)
                return config_ini.getvalue()
538969
def create_node(xml_node: XmlNode, **init_args):
    ''''''
    inst_type = get_inst_type(xml_node)
    init_args['xml_node'] = xml_node
    inst = create_inst(inst_type, **init_args)
    if not isinstance(inst, Node):
        inst = convert_to_node(inst, **init_args)
    return inst
660827
def get_init_file(dir):
    # type: (str) -> Optional[str]
    
    for ext in PY_EXTENSIONS:
        f = os.path.join(dir, '__init__' + ext)
        if os.path.isfile(f):
            return f
    return None