aboutsummaryrefslogtreecommitdiffstats
path: root/config_file/parsers/base_parser.py
blob: 38e885964ae9e68cf063295e3460c47225446db3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
from abc import ABC, abstractmethod


class BaseParser(ABC):
    """
    The abstract base parser for all other parsers to implement.

    All the keys are specified in a 'dot' syntax. So if you have
    sections with subsections with a key that you're trying to get
    the value of, you'd use 'section.subsection.key' as the key parameter.
    """

    @abstractmethod
    def __init__(self, file_contents: str):
        """
        All parsers will take in the file as a string, parse
        them internally to their own representation that they
        can work with, and are able to stringify them back out
        when we need to save (write) them.

        It is up to the caller of the parser to read in the file to
        the parser and save the file when they are done using stringify().
        """
        self.contents = file_contents
        self.parse(self.contents)

    @abstractmethod
    def get(self, key, parse_type=True):
        """
        Retrieve the value of a key in its native type.
        This means the string 'true' will be parsed back as the
        boolean True.

        If parse_type is set to False, all values will be returned
        back as strings.
        """
        raise NotImplementedError

    @abstractmethod
    def set(self, key, value):
        """Sets the value of a key."""
        raise NotImplementedError

    @abstractmethod
    def delete(self, section_key):
        """Deletes a key/value pair or entire sections."""
        raise NotImplementedError

    @abstractmethod
    def stringify(self) -> str:
        """
        Using self.__contents, converts the parsed internal representation
        of the file back into a string.
        """
        raise NotImplementedError

    @abstractmethod
    def has(self, section_key: str) -> bool:
        """
        Check if a section, sub-section, or key exists in the file
        using a section.key format.

        Some formats, like JSON, do not have sections and therefore,
        it would only be checking if
        """
        raise NotImplementedError

    @abstractmethod
    def parse(self, file_contents: str):
        """
        Parse the file_contents into an internal representation
        the given parser can work with. It should not return anything
        if you're going to be using the super() constructor.
        """
        raise NotImplementedError

    @staticmethod
    def _split_on_dot(line: str, all_dots=False):
        """
        Split a string on the first dot (.).

        :param line: The line ot split on.
        :param all_dots: If the line should be split on all the dots. Defaults to
                         False and only splits on the first occurrence of one.

        :raises ValueError: if the line does not have a dot.
        """
        if "." not in line:
            raise ValueError(
                "section_key must contain the section and key separated by a dot. "
                + "e.g. 'section.key'"
            )

        return line.split(".") if all_dots else line.rsplit(".", 1)


class ParsingError(Exception):
    """Unable to parse the configuration file"""