]> git.ipfire.org Git - nitsi.git/blame - src/nitsi/settings.py
Add include_path as setting
[nitsi.git] / src / nitsi / settings.py
CommitLineData
f33494aa
JS
1#!/usr/bin/python3
2
3import logging
4import os
7aa9213e 5import configparser
f33494aa
JS
6
7logger = logging.getLogger("nitsi.settings")
8
9class SettingsException(Exception):
10 def __init__(self, message):
11 self.message = message
12
13def settings_parse_copy_from(copy_from, path=None):
14 logger.debug("Going to parse the copy_from setting.")
15
16 # Check if we already get a list:
17 if not isinstance(copy_from, list):
18 copy_from = copy_from.split(" ")
19
20 tmp = []
21 for file in copy_from:
22 file = file.strip()
23 # If file is empty we do not want to add it to the list
24 if not file == "":
25 # If we get an absolut path we do nothing
26 # If not we add self.path to get an absolut path
27 if not os.path.isabs(file):
28 if path:
29 file = os.path.normpath(path + "/" + file)
30 else:
31 file = os.path.abspath(file)
32
33 logger.debug("Checking if '{}' is a valid file or dir".format(file))
34 # We need to check if file is a valid file or dir
35 if not (os.path.isdir(file) or os.path.isfile(file)):
36 raise SettingsException("'{}' is not a valid file nor a valid directory".format(file))
37
38 logger.debug("'{}' will be copied into all images".format(file))
39 tmp.append(file)
40
7aa9213e
JS
41 return tmp
42
43class CommonSettings():
44 def __init__(self, priority_list=[]):
45 if "cache" in priority_list:
46 raise SettingsException("Cache is reserved and so an invalid type")
47
48 self.priority_list = ["cache"] + priority_list
49
50 self._settings = {}
51
52 def set_config_value(self, key, value, type=None):
53 self.check_type(type)
54
55 # Add value to the dict
56 self._settings[type].setdefault(key, value)
57 logger.debug("Added key '{}' with value '{}' of type {} to settings".format(key, value, type))
58
59 # If this key is in the cache and type is not "cache" we need to refresh the cache
60 if "cache" in self._settings and type != "cache":
61 if key in self._settings["cache"]:
62 logger.debug("Removing key '{}' of cache because of new value".format(key))
63 self._settings["cache"].pop(key)
64
65 def get_config_value(self, key):
66 # loop through the priority list and try to find the config value
67
68 for type in self.priority_list:
69 if type in self._settings:
70 if key in self._settings[type]:
71 logger.debug("Found key '{}' in '{}'".format(key, type))
72 value = self._settings[type].get(key)
73 break
74
75 # Update cache:
76 if type != "cache":
77 self.set_config_value(key, value, type="cache")
78
79 return value
80
81 # checks if a type passed to a set_* function is valid
82 def check_type(self, type):
83 if type == None:
84 raise SettingsException("Type for a new config value cannot be None")
85
86 if type not in self.priority_list:
87 raise SettingsException("Type {} is not a valid type".format(type))
88
89 # Add a new type to the settings dict
90 if type not in self._settings:
91 self._settings.setdefault(type, {})
92
93# A settings class with some nitsi defaults
94class NitsiSettings(CommonSettings):
95 def __init__(self, priority_list=[]):
96 super().__init__(priority_list)
97
98 # Set default settings
99 self.set_config_value("name", "", type="nitsi-default")
100 self.set_config_value("description", "", type="nitsi-default")
101 self.set_config_value("copy_from", None, type="nitsi-default")
102 self.set_config_value("copy_to", None, type="nitsi-default")
103 self.set_config_value("virtual_environ_path", None, type="nitsi-default")
104 self.set_config_value("interactive_error_handling", False, type="nitsi-default")
ca4917b4 105 self.set_config_value("include_path", None, type="nitsi-default")
7aa9213e
JS
106
107 def set_config_values_from_file(self, file, type):
108 self.check_type(type)
109
3b2a454a 110 logger.debug("Path of settings file is: {}".format(file))
7aa9213e
JS
111 # Check that file is an valid file
112 if not os.path.isfile(file):
113 raise SettingsException("No such file: {}".format(file))
114
115 # Check that we are use an absolut path
116 if not os.path.isabs(file):
117 file = os.path.abspath(file)
118
119 try:
120 config = configparser.ConfigParser()
121 config.read(file)
122 except BaseException as e:
123 raise e
124
125 if "GENERAL" in config:
ca4917b4 126 for key in ["name", "description", "copy_to", "copy_from", "include_path"]:
7aa9213e
JS
127 if key in config["GENERAL"]:
128 # Handle the copy from setting in a special way
129 if key == "copy_from":
130 self.set_config_value(key, settings_parse_copy_from(config["GENERAL"][key], path=os.path.dirname(file)), type=type)
ca4917b4
JS
131 elif key == "include_path":
132 self.set_config_value(key, os.path.normpath(os.path.dirname(file) + "/" + config["GENERAL"][key]), type=type)
7aa9213e
JS
133 else:
134 self.set_config_value(key, config["GENERAL"][key], type=type)
135
136
137 if "VIRTUAL_ENVIRONMENT" in config:
138 if "path" in config["VIRTUAL_ENVIRONMENT"]:
139 path = config["VIRTUAL_ENVIRONMENT"]["path"]
140 if not os.path.isabs(path):
141 path = os.path.normpath(os.path.dirname(file) + "/" + path)
142 self.set_config_value("virtual_environ_path", path, type=type)
143
144
145 def check_config_values(self):
146 # Check if we get at least a valid a valid path to virtual environ
147 if not os.path.isdir(self.get_config_value("virtual_environ_path")):
148 raise SettingsException("No path for virtual environment found.")