aboutsummaryrefslogtreecommitdiff
path: root/configuration.py
blob: 78cce27dad4d38c48ba49d3a4ad4a9c50ed4337c (plain)
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
""" The configuration from the user.
"""

from collections import OrderedDict
from os import path
import json
from zope import component
from interfaces.message import Error
class Mapping():
    """Represent the configuration. This class is provided as an utility and is
       used in the IDesktop interfaces.
    """

    def __init__(self, configuration):
        self.init_mapping = configuration["mapping"]
        self.mapping = OrderedDict()
        tmp_mapping = dict(self.init_mapping)
        for key in tmp_mapping.keys() :
            json_file = self.init_mapping[key]
            if not path.exists(json_file):
                component.handle(Error(f"The file '{json_file}' does not exists"))
                continue
            with open(json_file, "r") as file:
                json_data = file.read()
                j = json.loads(json_data)
                self.mapping[key] = j

    def reset(self):
        """ Remove all the keys added and not in the configuration file.
        """
        # Create a copy of the dictonnary before updating the keys
        tmp_mapping = dict(self.mapping)
        for key in tmp_mapping.keys() :
            if key not in self.init_mapping.keys():
                del self.mapping[key]

    def get(self, key, default):
        """ This function return the mapping associated with the given key.
        """
        return self.mapping.get(key, default)

    def __getitem__(self, key):
        return self.mapping.get(key, None)

    def __setitem__(self, key, value):
        self.mapping[key] = value

    def items(self):
        """ Implement the keys items from the dictionnary
        """
        return self.mapping.items()

    def keys(self):
        """ Implement the keys method from the dictionnary
        """
        return self.mapping.keys()