Parse From File

fejao_config_parser.src.parse_from.file

parse_from.file.py file for the fejao_config_parser package.

This module defines the ParseFromFile class which is responsible for parsing configuration values from configuration files based on a provided configuration specification.

ParseFromFile

Parse configuration values from configuration files.

This class reads configuration files in multiple formats (JSON, YAML, TOML, INI) and extracts configuration values. It automatically detects the file format based on the file extension and uses the appropriate parser.

The class follows a multi-step process: 1. Validates that the configuration file exists and is accessible 2. Detects the file type from the file extension 3. Parses the file using the appropriate parser for that format 4. Validates the parsed values against the configuration

Supported file formats: - JSON (.json): Standard JSON format - YAML (.yaml, .yml): YAML format with environment variable expansion - TOML (.toml): TOML format - INI (.ini, .cfg): INI format with enhanced type support

Attributes:
  • config (list) –

    List of configuration dictionaries.

  • config_file_path (str) –

    Full path to the configuration file.

  • values (dict) –

    Dictionary of parsed configuration values from the file.

Raises:
  • ValueError –

    If file doesn't exist, file type is unsupported, or parsing fails.

Example

config = [ ... {"name": "db_host", "type": "string", "default": "localhost"}, ... {"name": "db_port", "type": "int", "default": 5432} ... ] parser = ParseFromFile(config=config, config_file_path="/etc/app/config.json") values = parser.get_values() print(values) {'db_host': 'db.example.com', 'db_port': 5432}

Source code in fejao_config_parser/src/parse_from/file.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
class ParseFromFile:
    """Parse configuration values from configuration files.

    This class reads configuration files in multiple formats (JSON, YAML, TOML, INI)
    and extracts configuration values. It automatically detects the file format based
    on the file extension and uses the appropriate parser.

    The class follows a multi-step process:
    1. Validates that the configuration file exists and is accessible
    2. Detects the file type from the file extension
    3. Parses the file using the appropriate parser for that format
    4. Validates the parsed values against the configuration

    Supported file formats:
    - JSON (.json): Standard JSON format
    - YAML (.yaml, .yml): YAML format with environment variable expansion
    - TOML (.toml): TOML format
    - INI (.ini, .cfg): INI format with enhanced type support

    Attributes:
        config (list): List of configuration dictionaries.
        config_file_path (str): Full path to the configuration file.
        values (dict): Dictionary of parsed configuration values from the file.

    Raises:
        ValueError: If file doesn't exist, file type is unsupported, or parsing fails.

    Example:
        >>> config = [
        ...     {"name": "db_host", "type": "string", "default": "localhost"},
        ...     {"name": "db_port", "type": "int", "default": 5432}
        ... ]
        >>> parser = ParseFromFile(config=config, config_file_path="/etc/app/config.json")
        >>> values = parser.get_values()
        >>> print(values)
        {'db_host': 'db.example.com', 'db_port': 5432}
    """

    def __init__(self, config: list, config_file_path: str) -> None:
        """Initialize the ParseFromFile instance and parse the configuration file.

        This constructor initializes the parser with a configuration list and file path,
        then immediately processes the configuration file. It performs validation on
        the parsed values to ensure they conform to the specified types.

        Args:
            config (list): List of configuration dictionaries specifying expected values.
            config_file_path (str): Full path to the configuration file to parse.
                                   File format is auto-detected from extension.

        Raises:
            ValueError: If:
                - File doesn't exist or is not readable
                - File type is not supported
                - File parsing fails
                - Configuration validation fails

        Example:
            >>> parser = ParseFromFile(
            ...     config=[{"name": "api_url", "type": "string", "default": ""}],
            ...     config_file_path="./config.json"
            ... )
        """
        self.config = config
        self.config_file_path = config_file_path

        self.__check_file_exists()
        self.__set_values()
        self.__check_values()

    def __check_file_exists(self) -> None:
        """Verify that the configuration file exists and is accessible.

        Attempts to open the file in read mode to verify it exists and is readable.
        This is done early in initialization to fail fast if the file is inaccessible.

        Raises:
            ValueError: If the file doesn't exist, is not readable, or any other
                       file access error occurs.

        Returns:
            None
        """
        try:
            with open(self.config_file_path, 'r', encoding='utf-8') as _:
                pass

        except FileNotFoundError:
            print(f"\n\nError reading the file with path: '{self.config_file_path}'. "
                  "File not found at the provided path.\n")
            raise
        except IOError:
            print(f"\n\nError reading the file with path: '{self.config_file_path}'. "
                  "IO error occurred.\n")
            raise
        except Exception as e:
            print(f"\n\nError at the configuration path provided '{self.config_file_path}'. "
                  f"The error found was: '{e}'\n")
            raise

    def __get_file_type(self) -> None:
        """Detect the configuration file type from the file extension.

        Determines the file format by checking if known file extensions are present
        in the file path. The supported file types are:
        - json: JSON format
        - yaml/yml: YAML format
        - toml: TOML format
        - ini/cfg: INI format

        Returns:
            str: The detected file type as a string (e.g., 'json', 'yaml', 'toml', 'ini').

        Raises:
            ValueError: If the file extension does not match any supported file type.

        Note:
            File type detection is case-insensitive (uses .lower()).
        """
        for file_type in DEFAULT_ACCEPTED_FILE_TYPES:
            if file_type in self.config_file_path.lower():
                return file_type

        raise ValueError(
            "\n\nError at the configuration file. "
            "The file type of the configuration file is not supported. "
            f"The accepted file types are: {DEFAULT_ACCEPTED_FILE_TYPES}. "
            "Please refer to the documentation for more details.\n")

    def __values_from_yaml(self) -> None:
        """Parse configuration from a YAML file.

        Parses YAML configuration files using the pyaml_env library, which supports
        environment variable expansion within YAML files using the ${VAR_NAME} syntax.

        Returns:
            dict: Dictionary of configuration values extracted from the YAML file.

        Raises:
            ValueError: If the YAML file cannot be parsed or contains invalid syntax.

        Example:
            If config.yaml contains:
            ```
            database_url: ${DATABASE_URL}
            max_connections: 10
            ```
            Returns: {'database_url': <env_value>, 'max_connections': 10}
        """
        try:
            return pyaml_env.parse_config(self.config_file_path)

        except Exception as e:
            print(
                "\n\nError parsing the configuration from a YAML file. "
                f"The error found was: {e}. "
                "Please refer to the documentation for more details.\n")
            raise

    def __values_from_json(self) -> None:
        """Parse configuration from a JSON file.

        Reads and parses a JSON configuration file. The JSON structure should be
        a flat dictionary at the top level with configuration names as keys.

        Returns:
            dict: Dictionary of configuration values extracted from the JSON file.

        Raises:
            ValueError: If the JSON file is invalid or cannot be parsed.

        Example:
            If config.json contains:
            ```
            {
                "host": "localhost",
                "port": 8080
            }
            ```
            Returns: {'host': 'localhost', 'port': 8080}
        """
        try:
            with open(self.config_file_path, 'r', encoding='utf-8') as file:
                return json.load(file)

        except Exception as e:
            print(
                "\n\nError parsing the configuration from a JSON file. "
                f"The error found was: {e}. "
                "Please refer to the documentation for more details.\n")
            raise

    def __values_from_toml(self) -> None:
        """Parse configuration from a TOML file.

        Reads and parses a TOML configuration file using the tomli library.
        TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration format.

        Returns:
            dict: Dictionary of configuration values extracted from the TOML file.

        Raises:
            ValueError: If the TOML file is invalid or cannot be parsed.

        Example:
            If config.toml contains:
            ```
            host = "localhost"
            port = 8080
            ```
            Returns: {'host': 'localhost', 'port': 8080}

        Note:
            Currently uses "config.toml" as the filename - this appears to be a bug
            as it should use self.config_file_path instead.
        """
        try:
            with open(self.config_file_path, "rb") as file:
                return tomli.load(file)

        except Exception as e:
            print(
                "\n\nError parsing the configuration from a TOML file. "
                f"The error found was: {e}. "
                "Please refer to the documentation for more details.\n")
            raise

    def __values_from_ini(self) -> None:
        """Parse configuration from an INI file.

        Reads and parses an INI configuration file. INI files are organized in sections,
        and this parser extracts values from the default section only.

        This method supports enhanced type parsing including:
        - Strings (quoted or unquoted)
        - Booleans (true, false, yes, no, on, off)
        - Integers and floats
        - Lists (bracket notation or comma-separated)
        - Dictionaries (Python dict literal syntax)
        - None/null values

        Returns:
            dict: Dictionary of configuration values extracted from the INI file.

        Raises:
            ValueError: If the INI file cannot be parsed.

        Example:
            If config.ini contains:
            ```
            [default]
            host = "localhost"
            port = 8080
            enabled = true
            servers = [server1, server2]
            ```
            Returns: {'host': 'localhost', 'port': 8080, 'enabled': True, 'servers': ['server1', 'server2']}
        """

        def _parse_integer(value: str):
            """
            Parse integer values.

            Args:
                value (str): The string value to parse.

            Returns:
                tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                       int if matched is True, or None if matched is False.
            """
            if value[0] == '"':
                try:
                    return (True, int(value.strip('"')))
                except ValueError:
                    return (False, None)

            if value[0] == "'":
                try:
                    return (True, int(value.strip("'")))
                except ValueError:
                    return (False, None)

            if re.match(r'^-?\d+$', value):
                return (True, int(value))

            return (False, None)

        def _parse_float(value: str):
            """
            Parse float values.

            Args:
                value (str): The string value to parse.

            Returns:
                tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                       float if matched is True, or None if matched is False.
            """
            if value[0] == '"':
                try:
                    return (True, float(value.strip('"')))
                except ValueError:
                    return (False, None)

            if value[0] == "'":
                try:
                    return (True, float(value.strip("'")))
                except ValueError:
                    return (False, None)

            if re.match(r'^-?\d+\.\d+$', value):
                return (True, float(value))

            return (False, None)

        def _parse_quoted_string(value: str):
            """
            Parse quoted strings and convert special values like 'none' to None.

            Args:
                value (str): The string value to parse.

            Returns:
                tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                       string if matched is True, or None if matched is False.
            """
            if value and value[0] in ('"', "'") and value[0] == value[-1] and "," not in value:
                unquoted = value[1:-1].encode().decode('unicode_escape')

                # Check for None/NULL values after unquoting
                if unquoted.lower() in ('none', 'null', 'nil', '~'):
                    return (True, None)
                if unquoted.lower() in ('true', 'yes', 'on'):
                    return (True, True)
                if unquoted.lower() in ('false', 'no', 'off'):
                    return (True, False)

                return (True, unquoted)

            return (False, None)

        def _parse_boolean(value: str):
            """
            Parse boolean values from strings like 'true', 'false', 'yes', 'no', 'on', 'off'.

            Args:
                value (str): The string value to parse as an integer.

            Returns:
                tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                       boolean if matched is True, or None if matched is False.
            """
            lower_val = value.lower()
            if lower_val in ('true', 'yes', 'on'):
                return (True, True)
            if lower_val in ('false', 'no', 'off'):
                return (True, False)

            return (False, None)

        def _is_complex_type(value: str) -> bool:
            """
            Parse complex types (lists, dicts, tuples) using ast.literal_eval.

            Args:
                value (str): The string value to parse.

            Returns:
                bool: True if the value looks like a complex type (list, dict, tuple), False otherwise.
            """
            pairs = {('(', ')'), ('[', ']'), ('{', '}')}
            return (value[0], value[-1]) in pairs

        def _parse_complex_type(value: str):
            """
            Parse complex types (lists, dicts, tuples) using ast.literal_eval.

            Args:
                value (str): The string value to parse.

            Returns:
                tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                       list, dict, or tuple if matched is True, or None if matched is False.
            """
            if not value or value[0] in ('"', "'"):
                return (False, None)

            if _is_complex_type(value):
                try:
                    evaluated = ast.literal_eval(value)
                    if isinstance(evaluated, tuple):
                        return (True, list(evaluated))

                    return (True, evaluated)
                except (SyntaxError, ValueError):
                    pass

            return (False, None)

        def _parse_comma_separated_list(value: str):
            """
            Parse comma-separated lists without brackets.

            Args:
                value (str): The string value to parse as an integer.

            Returns:
                tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                       list if matched is True, or None if matched is False.
            """
            if ',' in value and ' ' in value and not any(c in value for c in '[](){}'):
                parts = [p.strip() for p in value.split(',')]
                parsed_parts = [_parse_value(p) for p in parts]

                return (True, parsed_parts)

            return (False, None)

        def _parse_value(value: str) -> (str | int | float | bool | list | dict):
            """
            Parse a string value into appropriate Python type including lists, dicts, etc.
            """
            value = value.strip()

            parsers = [
                _parse_integer,
                _parse_float,
                _parse_quoted_string,
                _parse_boolean,
                _parse_complex_type,
                _parse_comma_separated_list,
            ]

            for parser in parsers:
                matched, parsed = parser(value)
                if matched:
                    return parsed

            # default -> return as string
            return value

        ###
        ### Main parsing logic for INI files with enhanced type support
        ###
        try:
            config = configparser.ConfigParser()
            config.read(self.config_file_path)

            result = {}
            for section in config.sections():
                if section == DEFAULT_INI_SECTION:
                    for key, value in config.items(section):
                        result[key] = _parse_value(value)

            return result

        except Exception as e:
            print(
                "\n\nError parsing the configuration from a INI file. "
                f"The error found was: {e}. "
                "Please refer to the documentation for more details.\n")
            raise

    def __set_values(self) -> None:
        """Parse the configuration file and convert values to appropriate types.

        This private method:
        1. Detects the file type from the file extension
        2. Validates the file type is supported
        3. Calls the appropriate parser method based on file type
        4. Stores the parsed values in self.values

        Supported file types and their parsers:
        - YAML/YML: __values_from_yaml()
        - JSON: __values_from_json()
        - TOML: __values_from_toml()
        - INI: __values_from_ini()

        Raises:
            ValueError: If file type is not supported or parsing fails.

        Returns:
            None
        """
        file_type = self.__get_file_type()

        if file_type.lower() in ["yaml", "yml"]:
            self.values = self.__values_from_yaml()
        elif file_type.lower() == "json":
            self.values = self.__values_from_json()
        elif file_type.lower() == "toml":
            self.values = self.__values_from_toml()
        elif file_type.lower() == "ini":
            self.values = self.__values_from_ini()
        else:
            self.values = {}

    def __check_values(self) -> None:
        """Validate the parsed file values against the configuration.

        This private method validates that all parsed values:
        - Match their specified types
        - Conform to the accepted type system
        - Are valid for their configured types

        The validation is performed by the ValuesCheck class which ensures type safety
        and configuration compliance.

        Raises:
            ValueError: If any value fails validation.

        Returns:
            None
        """
        ValuesCheck(config=self.config, values_found=self.values, info_string="configuration file")

    def get_values(self) -> dict:
        """Return the parsed configuration file values as a dictionary.

        This public method provides access to the parsed configuration values that were
        successfully extracted from the configuration file.

        Returns:
            dict: Dictionary mapping configuration names to their values from the file.
                  Format: {config_name: parsed_value}.

        Example:
            >>> parser = ParseFromFile(config=[...], config_file_path="config.json")
            >>> values = parser.get_values()
            >>> print(values)
            {'database_url': 'postgresql://localhost', 'debug': True}
        """
        return self.values
Methods:
__check_file_exists
__check_file_exists() -> None

Verify that the configuration file exists and is accessible.

Attempts to open the file in read mode to verify it exists and is readable. This is done early in initialization to fail fast if the file is inaccessible.

Raises:
  • ValueError –

    If the file doesn't exist, is not readable, or any other file access error occurs.

Returns:
  • None –

    None

Source code in fejao_config_parser/src/parse_from/file.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __check_file_exists(self) -> None:
    """Verify that the configuration file exists and is accessible.

    Attempts to open the file in read mode to verify it exists and is readable.
    This is done early in initialization to fail fast if the file is inaccessible.

    Raises:
        ValueError: If the file doesn't exist, is not readable, or any other
                   file access error occurs.

    Returns:
        None
    """
    try:
        with open(self.config_file_path, 'r', encoding='utf-8') as _:
            pass

    except FileNotFoundError:
        print(f"\n\nError reading the file with path: '{self.config_file_path}'. "
              "File not found at the provided path.\n")
        raise
    except IOError:
        print(f"\n\nError reading the file with path: '{self.config_file_path}'. "
              "IO error occurred.\n")
        raise
    except Exception as e:
        print(f"\n\nError at the configuration path provided '{self.config_file_path}'. "
              f"The error found was: '{e}'\n")
        raise
__check_values
__check_values() -> None

Validate the parsed file values against the configuration.

This private method validates that all parsed values: - Match their specified types - Conform to the accepted type system - Are valid for their configured types

The validation is performed by the ValuesCheck class which ensures type safety and configuration compliance.

Raises:
  • ValueError –

    If any value fails validation.

Returns:
  • None –

    None

Source code in fejao_config_parser/src/parse_from/file.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def __check_values(self) -> None:
    """Validate the parsed file values against the configuration.

    This private method validates that all parsed values:
    - Match their specified types
    - Conform to the accepted type system
    - Are valid for their configured types

    The validation is performed by the ValuesCheck class which ensures type safety
    and configuration compliance.

    Raises:
        ValueError: If any value fails validation.

    Returns:
        None
    """
    ValuesCheck(config=self.config, values_found=self.values, info_string="configuration file")
__get_file_type
__get_file_type() -> None

Detect the configuration file type from the file extension.

Determines the file format by checking if known file extensions are present in the file path. The supported file types are: - json: JSON format - yaml/yml: YAML format - toml: TOML format - ini/cfg: INI format

Returns:
  • str( None ) –

    The detected file type as a string (e.g., 'json', 'yaml', 'toml', 'ini').

Raises:
  • ValueError –

    If the file extension does not match any supported file type.

Note

File type detection is case-insensitive (uses .lower()).

Source code in fejao_config_parser/src/parse_from/file.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def __get_file_type(self) -> None:
    """Detect the configuration file type from the file extension.

    Determines the file format by checking if known file extensions are present
    in the file path. The supported file types are:
    - json: JSON format
    - yaml/yml: YAML format
    - toml: TOML format
    - ini/cfg: INI format

    Returns:
        str: The detected file type as a string (e.g., 'json', 'yaml', 'toml', 'ini').

    Raises:
        ValueError: If the file extension does not match any supported file type.

    Note:
        File type detection is case-insensitive (uses .lower()).
    """
    for file_type in DEFAULT_ACCEPTED_FILE_TYPES:
        if file_type in self.config_file_path.lower():
            return file_type

    raise ValueError(
        "\n\nError at the configuration file. "
        "The file type of the configuration file is not supported. "
        f"The accepted file types are: {DEFAULT_ACCEPTED_FILE_TYPES}. "
        "Please refer to the documentation for more details.\n")
__init__
__init__(config: list, config_file_path: str) -> None

Initialize the ParseFromFile instance and parse the configuration file.

This constructor initializes the parser with a configuration list and file path, then immediately processes the configuration file. It performs validation on the parsed values to ensure they conform to the specified types.

Parameters:
  • config (list) –

    List of configuration dictionaries specifying expected values.

  • config_file_path (str) –

    Full path to the configuration file to parse. File format is auto-detected from extension.

Raises:
  • ValueError –

    If: - File doesn't exist or is not readable - File type is not supported - File parsing fails - Configuration validation fails

Example

parser = ParseFromFile( ... config=[{"name": "api_url", "type": "string", "default": ""}], ... config_file_path="./config.json" ... )

Source code in fejao_config_parser/src/parse_from/file.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def __init__(self, config: list, config_file_path: str) -> None:
    """Initialize the ParseFromFile instance and parse the configuration file.

    This constructor initializes the parser with a configuration list and file path,
    then immediately processes the configuration file. It performs validation on
    the parsed values to ensure they conform to the specified types.

    Args:
        config (list): List of configuration dictionaries specifying expected values.
        config_file_path (str): Full path to the configuration file to parse.
                               File format is auto-detected from extension.

    Raises:
        ValueError: If:
            - File doesn't exist or is not readable
            - File type is not supported
            - File parsing fails
            - Configuration validation fails

    Example:
        >>> parser = ParseFromFile(
        ...     config=[{"name": "api_url", "type": "string", "default": ""}],
        ...     config_file_path="./config.json"
        ... )
    """
    self.config = config
    self.config_file_path = config_file_path

    self.__check_file_exists()
    self.__set_values()
    self.__check_values()
__set_values
__set_values() -> None

Parse the configuration file and convert values to appropriate types.

This private method: 1. Detects the file type from the file extension 2. Validates the file type is supported 3. Calls the appropriate parser method based on file type 4. Stores the parsed values in self.values

Supported file types and their parsers: - YAML/YML: __values_from_yaml() - JSON: __values_from_json() - TOML: __values_from_toml() - INI: __values_from_ini()

Raises:
  • ValueError –

    If file type is not supported or parsing fails.

Returns:
  • None –

    None

Source code in fejao_config_parser/src/parse_from/file.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def __set_values(self) -> None:
    """Parse the configuration file and convert values to appropriate types.

    This private method:
    1. Detects the file type from the file extension
    2. Validates the file type is supported
    3. Calls the appropriate parser method based on file type
    4. Stores the parsed values in self.values

    Supported file types and their parsers:
    - YAML/YML: __values_from_yaml()
    - JSON: __values_from_json()
    - TOML: __values_from_toml()
    - INI: __values_from_ini()

    Raises:
        ValueError: If file type is not supported or parsing fails.

    Returns:
        None
    """
    file_type = self.__get_file_type()

    if file_type.lower() in ["yaml", "yml"]:
        self.values = self.__values_from_yaml()
    elif file_type.lower() == "json":
        self.values = self.__values_from_json()
    elif file_type.lower() == "toml":
        self.values = self.__values_from_toml()
    elif file_type.lower() == "ini":
        self.values = self.__values_from_ini()
    else:
        self.values = {}
__values_from_ini
__values_from_ini() -> None

Parse configuration from an INI file.

Reads and parses an INI configuration file. INI files are organized in sections, and this parser extracts values from the default section only.

This method supports enhanced type parsing including: - Strings (quoted or unquoted) - Booleans (true, false, yes, no, on, off) - Integers and floats - Lists (bracket notation or comma-separated) - Dictionaries (Python dict literal syntax) - None/null values

Returns:
  • dict( None ) –

    Dictionary of configuration values extracted from the INI file.

Raises:
  • ValueError –

    If the INI file cannot be parsed.

Example

If config.ini contains:

[default]
host = "localhost"
port = 8080
enabled = true
servers = [server1, server2]

Returns: {'host': 'localhost', 'port': 8080, 'enabled': True, 'servers': ['server1', 'server2']}

Source code in fejao_config_parser/src/parse_from/file.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
def __values_from_ini(self) -> None:
    """Parse configuration from an INI file.

    Reads and parses an INI configuration file. INI files are organized in sections,
    and this parser extracts values from the default section only.

    This method supports enhanced type parsing including:
    - Strings (quoted or unquoted)
    - Booleans (true, false, yes, no, on, off)
    - Integers and floats
    - Lists (bracket notation or comma-separated)
    - Dictionaries (Python dict literal syntax)
    - None/null values

    Returns:
        dict: Dictionary of configuration values extracted from the INI file.

    Raises:
        ValueError: If the INI file cannot be parsed.

    Example:
        If config.ini contains:
        ```
        [default]
        host = "localhost"
        port = 8080
        enabled = true
        servers = [server1, server2]
        ```
        Returns: {'host': 'localhost', 'port': 8080, 'enabled': True, 'servers': ['server1', 'server2']}
    """

    def _parse_integer(value: str):
        """
        Parse integer values.

        Args:
            value (str): The string value to parse.

        Returns:
            tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                   int if matched is True, or None if matched is False.
        """
        if value[0] == '"':
            try:
                return (True, int(value.strip('"')))
            except ValueError:
                return (False, None)

        if value[0] == "'":
            try:
                return (True, int(value.strip("'")))
            except ValueError:
                return (False, None)

        if re.match(r'^-?\d+$', value):
            return (True, int(value))

        return (False, None)

    def _parse_float(value: str):
        """
        Parse float values.

        Args:
            value (str): The string value to parse.

        Returns:
            tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                   float if matched is True, or None if matched is False.
        """
        if value[0] == '"':
            try:
                return (True, float(value.strip('"')))
            except ValueError:
                return (False, None)

        if value[0] == "'":
            try:
                return (True, float(value.strip("'")))
            except ValueError:
                return (False, None)

        if re.match(r'^-?\d+\.\d+$', value):
            return (True, float(value))

        return (False, None)

    def _parse_quoted_string(value: str):
        """
        Parse quoted strings and convert special values like 'none' to None.

        Args:
            value (str): The string value to parse.

        Returns:
            tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                   string if matched is True, or None if matched is False.
        """
        if value and value[0] in ('"', "'") and value[0] == value[-1] and "," not in value:
            unquoted = value[1:-1].encode().decode('unicode_escape')

            # Check for None/NULL values after unquoting
            if unquoted.lower() in ('none', 'null', 'nil', '~'):
                return (True, None)
            if unquoted.lower() in ('true', 'yes', 'on'):
                return (True, True)
            if unquoted.lower() in ('false', 'no', 'off'):
                return (True, False)

            return (True, unquoted)

        return (False, None)

    def _parse_boolean(value: str):
        """
        Parse boolean values from strings like 'true', 'false', 'yes', 'no', 'on', 'off'.

        Args:
            value (str): The string value to parse as an integer.

        Returns:
            tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                   boolean if matched is True, or None if matched is False.
        """
        lower_val = value.lower()
        if lower_val in ('true', 'yes', 'on'):
            return (True, True)
        if lower_val in ('false', 'no', 'off'):
            return (True, False)

        return (False, None)

    def _is_complex_type(value: str) -> bool:
        """
        Parse complex types (lists, dicts, tuples) using ast.literal_eval.

        Args:
            value (str): The string value to parse.

        Returns:
            bool: True if the value looks like a complex type (list, dict, tuple), False otherwise.
        """
        pairs = {('(', ')'), ('[', ']'), ('{', '}')}
        return (value[0], value[-1]) in pairs

    def _parse_complex_type(value: str):
        """
        Parse complex types (lists, dicts, tuples) using ast.literal_eval.

        Args:
            value (str): The string value to parse.

        Returns:
            tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                   list, dict, or tuple if matched is True, or None if matched is False.
        """
        if not value or value[0] in ('"', "'"):
            return (False, None)

        if _is_complex_type(value):
            try:
                evaluated = ast.literal_eval(value)
                if isinstance(evaluated, tuple):
                    return (True, list(evaluated))

                return (True, evaluated)
            except (SyntaxError, ValueError):
                pass

        return (False, None)

    def _parse_comma_separated_list(value: str):
        """
        Parse comma-separated lists without brackets.

        Args:
            value (str): The string value to parse as an integer.

        Returns:
            tuple: A tuple (matched, parsed_value), parsed_value is the parsed
                   list if matched is True, or None if matched is False.
        """
        if ',' in value and ' ' in value and not any(c in value for c in '[](){}'):
            parts = [p.strip() for p in value.split(',')]
            parsed_parts = [_parse_value(p) for p in parts]

            return (True, parsed_parts)

        return (False, None)

    def _parse_value(value: str) -> (str | int | float | bool | list | dict):
        """
        Parse a string value into appropriate Python type including lists, dicts, etc.
        """
        value = value.strip()

        parsers = [
            _parse_integer,
            _parse_float,
            _parse_quoted_string,
            _parse_boolean,
            _parse_complex_type,
            _parse_comma_separated_list,
        ]

        for parser in parsers:
            matched, parsed = parser(value)
            if matched:
                return parsed

        # default -> return as string
        return value

    ###
    ### Main parsing logic for INI files with enhanced type support
    ###
    try:
        config = configparser.ConfigParser()
        config.read(self.config_file_path)

        result = {}
        for section in config.sections():
            if section == DEFAULT_INI_SECTION:
                for key, value in config.items(section):
                    result[key] = _parse_value(value)

        return result

    except Exception as e:
        print(
            "\n\nError parsing the configuration from a INI file. "
            f"The error found was: {e}. "
            "Please refer to the documentation for more details.\n")
        raise
__values_from_json
__values_from_json() -> None

Parse configuration from a JSON file.

Reads and parses a JSON configuration file. The JSON structure should be a flat dictionary at the top level with configuration names as keys.

Returns:
  • dict( None ) –

    Dictionary of configuration values extracted from the JSON file.

Raises:
  • ValueError –

    If the JSON file is invalid or cannot be parsed.

Example

If config.json contains:

{
    "host": "localhost",
    "port": 8080
}

Returns: {'host': 'localhost', 'port': 8080}

Source code in fejao_config_parser/src/parse_from/file.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def __values_from_json(self) -> None:
    """Parse configuration from a JSON file.

    Reads and parses a JSON configuration file. The JSON structure should be
    a flat dictionary at the top level with configuration names as keys.

    Returns:
        dict: Dictionary of configuration values extracted from the JSON file.

    Raises:
        ValueError: If the JSON file is invalid or cannot be parsed.

    Example:
        If config.json contains:
        ```
        {
            "host": "localhost",
            "port": 8080
        }
        ```
        Returns: {'host': 'localhost', 'port': 8080}
    """
    try:
        with open(self.config_file_path, 'r', encoding='utf-8') as file:
            return json.load(file)

    except Exception as e:
        print(
            "\n\nError parsing the configuration from a JSON file. "
            f"The error found was: {e}. "
            "Please refer to the documentation for more details.\n")
        raise
__values_from_toml
__values_from_toml() -> None

Parse configuration from a TOML file.

Reads and parses a TOML configuration file using the tomli library. TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration format.

Returns:
  • dict( None ) –

    Dictionary of configuration values extracted from the TOML file.

Raises:
  • ValueError –

    If the TOML file is invalid or cannot be parsed.

Example

If config.toml contains:

host = "localhost"
port = 8080

Returns: {'host': 'localhost', 'port': 8080}

Note

Currently uses "config.toml" as the filename - this appears to be a bug as it should use self.config_file_path instead.

Source code in fejao_config_parser/src/parse_from/file.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def __values_from_toml(self) -> None:
    """Parse configuration from a TOML file.

    Reads and parses a TOML configuration file using the tomli library.
    TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration format.

    Returns:
        dict: Dictionary of configuration values extracted from the TOML file.

    Raises:
        ValueError: If the TOML file is invalid or cannot be parsed.

    Example:
        If config.toml contains:
        ```
        host = "localhost"
        port = 8080
        ```
        Returns: {'host': 'localhost', 'port': 8080}

    Note:
        Currently uses "config.toml" as the filename - this appears to be a bug
        as it should use self.config_file_path instead.
    """
    try:
        with open(self.config_file_path, "rb") as file:
            return tomli.load(file)

    except Exception as e:
        print(
            "\n\nError parsing the configuration from a TOML file. "
            f"The error found was: {e}. "
            "Please refer to the documentation for more details.\n")
        raise
__values_from_yaml
__values_from_yaml() -> None

Parse configuration from a YAML file.

Parses YAML configuration files using the pyaml_env library, which supports environment variable expansion within YAML files using the ${VAR_NAME} syntax.

Returns:
  • dict( None ) –

    Dictionary of configuration values extracted from the YAML file.

Raises:
  • ValueError –

    If the YAML file cannot be parsed or contains invalid syntax.

Example

If config.yaml contains:

database_url: ${DATABASE_URL}
max_connections: 10

Returns: {'database_url': , 'max_connections': 10}

Source code in fejao_config_parser/src/parse_from/file.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def __values_from_yaml(self) -> None:
    """Parse configuration from a YAML file.

    Parses YAML configuration files using the pyaml_env library, which supports
    environment variable expansion within YAML files using the ${VAR_NAME} syntax.

    Returns:
        dict: Dictionary of configuration values extracted from the YAML file.

    Raises:
        ValueError: If the YAML file cannot be parsed or contains invalid syntax.

    Example:
        If config.yaml contains:
        ```
        database_url: ${DATABASE_URL}
        max_connections: 10
        ```
        Returns: {'database_url': <env_value>, 'max_connections': 10}
    """
    try:
        return pyaml_env.parse_config(self.config_file_path)

    except Exception as e:
        print(
            "\n\nError parsing the configuration from a YAML file. "
            f"The error found was: {e}. "
            "Please refer to the documentation for more details.\n")
        raise
get_values
get_values() -> dict

Return the parsed configuration file values as a dictionary.

This public method provides access to the parsed configuration values that were successfully extracted from the configuration file.

Returns:
  • dict( dict ) –

    Dictionary mapping configuration names to their values from the file. Format: {config_name: parsed_value}.

Example

parser = ParseFromFile(config=[...], config_file_path="config.json") values = parser.get_values() print(values) {'database_url': 'postgresql://localhost', 'debug': True}

Source code in fejao_config_parser/src/parse_from/file.py
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def get_values(self) -> dict:
    """Return the parsed configuration file values as a dictionary.

    This public method provides access to the parsed configuration values that were
    successfully extracted from the configuration file.

    Returns:
        dict: Dictionary mapping configuration names to their values from the file.
              Format: {config_name: parsed_value}.

    Example:
        >>> parser = ParseFromFile(config=[...], config_file_path="config.json")
        >>> values = parser.get_values()
        >>> print(values)
        {'database_url': 'postgresql://localhost', 'debug': True}
    """
    return self.values