Esempio n. 1
0
    def fromString(self, string):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromString(): defined by Reader interface.
             *
             * @param  string $string
             * @return array|bool
             * @throws Exception\RuntimeException
             */
        """

        if not string:
            return {}

        self.directory = None

        ret = {}

        if "@include" in string:
            raise RuntimeException(
                "Json: Cannot Process @include When Reading From String")

        try:
            ret = json.loads(string)
        except Exception as e:
            raise RuntimeException("Json: Error Reading JSON string: %s" % e)

        if not isinstance(ret, dict):
            ret = {"DEFAULT": ret}

        return ret
Esempio n. 2
0
    def fromString(self, string):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromString(): defined by Reader interface.
             *
             * @param  string $string
             * @return array|bool
             * @throws Exception\RuntimeException
             */
        """

        if not string:
            return {}

        self.directory = None

        ini = ConfigParser()

        if "@include" in string:
            raise RuntimeException(
                "Ini: Cannot Process @include When Reading From String")

        try:
            ini.read_string(string)
        except configparser.Error as e:
            raise RuntimeException("Ini: Error Reading INI string: %s" % e)

        ret = Ini.configParserToDict(ini)

        return self.process(ret)
Esempio n. 3
0
    def processKey(self, key, value, ret):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * Process a key.
             *
             * @param  string $key
             * @param  string $value
             * @param  array  $config
             * @return array
             * @throws Exception\RuntimeException
             */
        """

        if self.nestSeparator in key:
            pieces = key.split(self.nestSeparator, 1)
            if not len(pieces[0]) or not len(pieces[1]):
                raise RuntimeException("Ini: Invalid Key \"%s\"" % key)
            elif not pieces[0] in ret:
                if pieces[0] == '0' and ret:
                    ret = {pieces[0]: ret}
                else:
                    ret[pieces[0]] = {}
            elif ((isinstance(ret[pieces[0]], dict)
                   and pieces[1] in ret[pieces[0]]) or
                  (not isinstance(ret[pieces[0]], dict) and ret[pieces[0]])):
                raise RuntimeException(
                    "Ini: Cannot Create Sub-Key for \"%s\" : \"%s\", as key already exists"
                    % (pieces[0], pieces[1]))

            self.processKey(pieces[1], value, ret[pieces[0]])
        else:
            ret[key] = value
Esempio n. 4
0
    def fromString(self, string):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromString(): defined by Reader interface.
             *
             * @param  string $string
             * @return array|bool
             * @throws Exception\RuntimeException
             */
        """

        if not string:
            return {}

        self.directory = None

        if "@include" in string:
            raise RuntimeException(
                "Xml: Cannot Process @include When Reading From String")

        try:
            self.root = ElementTree.fromstring(string)
        except ElementTree.ParseError as e:
            raise RuntimeException("Xml: Error Reading XML string: %s" % e)

        return self.process(self.root)
Esempio n. 5
0
    def fromFile(self, filename):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromFile(): defined by Reader interface.
             *
             * @see    ReaderInterface::fromFile()
             * @param  string $filename
             * @return array
             * @throws Exception\RuntimeException
             */
        """

        if not os.path.isfile(filename) and not os.access(filename, os.R_OK):
            raise RuntimeException(
                "Yaml: File %s Doesn't Exist or Not Readable" % filename)

        self.directory = os.path.dirname(filename.rstrip(os.sep)) or '.'

        conf = {}

        try:
            with open(filename, "r") as file:
                yamlcontent = file.read()
                if self.safe:
                    conf = yaml.safe_load(yamlcontent)
                else:
                    conf = yaml.load(yamlcontent)
        except yaml.YAMLError as e:
            raise RuntimeException("Yaml: Error Reading YAML file \"%s\": %s" %
                                   (filename, e))

        return self.process(conf)
Esempio n. 6
0
    def fromFile(self, filename):
        r"""
        Following is the header as given in zend-config::

            /**
             * fromFile(): defined by Reader interface.
             *
             * @see    ReaderInterface::fromFile()
             * @param  string $filename
             * @return array
             * @throws Exception\RuntimeException
             */
        """

        if not os.path.isfile(filename) or not os.access(filename, os.R_OK):
            raise RuntimeException(
                "Json: File %s Doesn't Exist or Not Readable" % filename)

        self.directory = os.path.dirname(filename.rstrip(os.sep)) or '.'

        ret = {}

        try:
            jsoncontent = ''
            with open(filename, "r") as file:
                for line in file:
                    if "@include" in line:
                        include = line.split(":")[1].strip()[1:-1]
                        if include[0] != '/':
                            include = os.path.join(self.directory, include)
                        if (not os.path.isfile(
                                os.path.join(self.directory, include))
                                or not os.access(
                                    os.path.join(self.directory, include),
                                    os.R_OK)):
                            raise RuntimeException(
                                "Json: File %s Doesn't Exist or Not Readable" %
                                os.path.join(self.directory, include))
                        with open(include, "r") as includedfile:
                            for includedline in includedfile:
                                jsoncontent += includedline
                    else:
                        jsoncontent += line

            ret = json.loads(jsoncontent)
        except Exception as e:
            raise RuntimeException("Json: Error Reading JSON file \"%s\": %s" %
                                   (filename, e))

        if not isinstance(ret, dict):
            ret = {"DEFAULT": ret}

        return ret
Esempio n. 7
0
    def fromFile(self, filename):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromFile(): defined by Reader interface.
             *
             * @see    ReaderInterface::fromFile()
             * @param  string $filename
             * @return array
             * @throws Exception\RuntimeException
             */
        """

        if not os.path.isfile(filename) or not os.access(filename, os.R_OK):
            raise RuntimeException(
                "Ini: File %s Doesn't Exist or Not Readable" % filename)

        self.directory = os.path.dirname(filename.rstrip(os.sep)) or '.'

        ini = ConfigParser()

        try:
            inicontent = ''
            with open(filename, "r") as file:
                for line in file:
                    if "@include" in line:
                        include = line.split("=")[1]
                        if include[0] != '/':
                            include = os.path.join(self.directory, include)
                        if (not os.path.isfile(
                                os.path.join(self.directory, include))
                                or not os.access(
                                    os.path.join(self.directory, include),
                                    os.R_OK)):
                            raise RuntimeException(
                                "Ini: File %s Doesn't Exist or Not Readable" %
                                os.path.join(self.directory, include))
                        with open(include, "r") as includedfile:
                            for includedline in includedfile:
                                inicontent += includedline
                    else:
                        inicontent += line

            ini.read_string(inicontent)
        except configparser.Error as e:
            raise RuntimeException("Ini: Error Reading INI file \"%s\": %s" %
                                   (filename, e))

        ret = Ini.configParserToDict(ini)

        return self.process(ret)
Esempio n. 8
0
    def loader(self, href, parse, encoding=None):
        """
        Load the XML file from a file location
        
        Args:
            href: absolute/relative location of the file
            parse: do we immediately parse the file
            encoding: useful if not parsing, decodes the file from this encoding
        
        Returns:
            The file decoded file data if not parsed, otherwise the the ElementTree.parsed() root
        """

        if href[0] != '/':
            href = os.path.join(self.directory, href)
        if not os.path.isfile(href) or not os.access(href, os.R_OK):
            raise RuntimeException(
                "Xml: File %s Doesn't Exist or Not Readable (xi)" % href)

        file = open(href)
        if parse == "xml":
            data = ElementTree.parse(file).getroot()
        else:
            data = file.read()
            if encoding:
                data = data.decode(encoding)
        file.close()
        return data
Esempio n. 9
0
    def fromString(self, string):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromString(): defined by Reader interface.
             *
             * @param  string $string
             * @return array|bool
             * @throws Exception\RuntimeException
             */
        """

        if not string:
            return {}

        self.directory = None

        conf = {}

        try:
            if self.safe:
                conf = yaml.safe_load(string)
            else:
                conf = yaml.load(string)
        except yaml.YAMLError as e:
            raise RuntimeException("Yaml: Error Reading YAML string: %s" % e)

        return self.process(conf)
Esempio n. 10
0
 def toFile(self, filename, config, exclusive=True):
     """
     CHANGELOG:
     objconfig v1.1: use portalocker to establish an exclusive lock if given
     
     Following is the header as given in zend-config::
     
         /**
          * toFile(): defined by Writer interface.
          *
          * @see    WriterInterface::toFile()
          * @param  string  $filename
          * @param  mixed   $config
          * @param  bool $exclusiveLock
          * @return void
          * @throws Exception\InvalidArgumentException
          * @throws Exception\RuntimeException
          */
     """
     
     if not ('toArray' in dir(config) and inspect.ismethod(config.toArray)) and not isinstance(config, dict):
         raise InvalidArgumentException("AbstractWriter: toFile() expects a dictionary or implementing toArray")
     
     if not filename:
         raise InvalidArgumentException("AbstractWriter: No Filename Specified")
     
     try:
         with open(filename, "w") as file:
             if exclusive:
                 portalocker.lock(file, portalocker.LOCK_EX)
             file.write(self.toString(config))
     except Exception as e:
         raise RuntimeException("AbstractWriter: Error Writing to \"%s\": %s" % (filename, e))
Esempio n. 11
0
 def processConfig(self, config):
     r"""
     Following is the header as given in zend-config::
     
         /**
          * @param array $config
          * @return string
          */
     """
     
     raise RuntimeException("AbstractWriter: processConfig not implemented in child class")
Esempio n. 12
0
    def fromFile(self, filename):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * fromFile(): defined by Reader interface.
             *
             * @see    ReaderInterface::fromFile()
             * @param  string $filename
             * @return array
             * @throws Exception\RuntimeException
             */
        """

        if not os.path.isfile(filename) and not os.access(filename, os.R_OK):
            raise RuntimeException(
                "Xml: File %s Doesn't Exist or Not Readable" % filename)

        self.directory = os.path.dirname(filename.rstrip(os.sep)) or '.'

        try:
            xmlcontent = ''
            with open(filename, "r") as file:
                for line in file:
                    if "@include" in line:
                        include = line.split(":")[1].strip()
                        with open(os.path.join(self.directory, include),
                                  "r") as includedfile:
                            for includedline in includedfile:
                                xmlcontent += includedline
                    else:
                        xmlcontent += line

            self.root = ElementTree.fromstring(xmlcontent)
            ElementInclude.include(self.root, self.loader)
        except ElementTree.ParseError as e:
            raise RuntimeException("Xml: Error Reading XML file \"%s\": %s" %
                                   (filename, e))

        return self.process(self.root)
Esempio n. 13
0
    def process(self, array):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * Process the array for @include
             *
             * @param  array $data
             * @return array
             * @throws Exception\RuntimeException
             */
        """

        for key, value in (array.items() if 'items' in dir(array) else array):
            if isinstance(value, (tuple, list, dict)):
                array[key] = self.process(value)
            elif "_@include" in key:
                if not self.directory:
                    raise RuntimeException(
                        "Yaml: Cannot Process @include When Reading From String"
                    )
                if (not os.path.isfile(os.path.join(self.directory, value))
                        and not os.access(os.path.join(self.directory, value),
                                          os.R_OK)):
                    raise RuntimeException(
                        "Yaml: File %s Doesn't Exist or Not Readable (@include)"
                        % value)
                conf = {}
                with open(os.path.join(self.directory, value), "r") as file:
                    yamlcontent = file.read()
                    if self.safe:
                        conf = yaml.safe_load(yamlcontent)
                    else:
                        conf = yaml.load(yamlcontent)
                del array[key]

                array = array_merge_recursive(array, self.process(conf))
        return array
Esempio n. 14
0
    def processValue(self, value):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * Process a single value
             *
             * @param  mixed $value
             * @return mixed
             */
        """

        raise RuntimeException(
            "ProcessorInterface: processValue not implemented in child class")
Esempio n. 15
0
    def process(self, value):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * Process the whole Config structure and recursively parse all its values.
             *
             * @param  Config $value
             * @return Config
             */
        """

        raise RuntimeException(
            "ProcessorInterface: process not implemented in child class")
Esempio n. 16
0
    def __setattr__(self, attribute, value):
        r"""
        Notes:
            Makes a new Config object if value implements key, value : items()
        
        Following is the header as given in zend-config::
        
            /**
             * Set a value in the config.
             *
             * Only allow setting of a property if $allowModifications  was set to true
             * on construction. Otherwise, throw an exception.
             *
             * @param  string $name
             * @param  mixed  $value
             * @return void
             * @throws Exception\RuntimeException
             */
        """

        if attribute == '_Config__allowModifications':
            self.__dict__['_Config__allowModifications'] = value
            return
        elif attribute == '_Config__data':
            self.__dict__['_Config__data'] = value
            return
        if self.__allowModifications:
            if isinstance(value, dict):
                self.__data[attribute] = Config(value, allowModifications=True)
            elif attribute is None:
                raise RuntimeException(
                    "Config: __setattr__ attribute must have name")
            else:
                self.__data[attribute] = value
        else:
            raise RuntimeException("Config: __setattr__ config is read only")
Esempio n. 17
0
    def prepareValue(self, value):
        r"""
        NOTE:
            Just converts to string (minus double-quotes)
        
        Following is the header as given in zend-config::
        
            /**
             * Prepare a value for INI.
             *
             * @param  mixed $value
             * @return string
             * @throws Exception\RuntimeException
             */
        """

        if '"' in str(value):
            raise RuntimeException("Ini: Value Cannot Contain Double Quotes")
        else:
            return str(value)
Esempio n. 18
0
    def processConfig(self, config):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * processConfig(): defined by AbstractWriter.
             *
             * @param  array $config
             * @return string
             * @throws Exception\RuntimeException
             */
        """

        config = config.toArray() if 'toArray' in dir(
            config) and inspect.ismethod(config.toArray) else config
        ret = ''
        try:
            ret = yaml.dump(config, default_flow_style=False)
        except Exception as e:
            raise RuntimeException("Yaml: unable to process config: %s" % e)

        return ret
Esempio n. 19
0
    def fromFile(self, filename):
        """Initialize configuration object from file."""

        raise RuntimeException(
            "ReaderInterface: fromFile not implemented in child class")
Esempio n. 20
0
    def fromString(self, string):
        """Initialize configuration object from a string."""

        raise RuntimeException(
            "ReaderInterface: fromString not implemented in child class")