]> git.ipfire.org Git - pakfire.git/blob - python/pakfire/config.py
467b36aa96f0a272e2095fe9f6df53b62c9bd01c
[pakfire.git] / python / pakfire / config.py
1 #!/usr/bin/python
2 ###############################################################################
3 # #
4 # Pakfire - The IPFire package management system #
5 # Copyright (C) 2011 Pakfire development team #
6 # #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
11 # #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
16 # #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 # #
20 ###############################################################################
21
22 import io
23 import os
24 import socket
25
26 from ConfigParser import ConfigParser
27
28 import logging
29 log = logging.getLogger("pakfire")
30
31 import logger
32 from system import system
33
34 from constants import *
35 from i18n import _
36
37 class _Config(object):
38 files = []
39
40 global_default_settings = {
41 "logger" : {
42 "file" : "/var/log/pakfire.log",
43 "level" : "normal",
44 "mode" : "rotate",
45 "rotation_threshold" : 10485760,
46 },
47 }
48
49 # A dict with default settings for this config class.
50 default_settings = {}
51
52 def __init__(self, files=None):
53 # Configuration settings.
54 self._config = self.global_default_settings.copy()
55 self._config.update(self.default_settings)
56
57 # List of files that were already loaded.
58 self._files = []
59
60 # If no files were given, load the default files.
61 if files is None:
62 # Read default configuration file.
63 self.read(*self.files)
64
65 repo_path = self.get(None, "repo_path", CONFIG_REPOS_DIR)
66 if repo_path:
67 self.read_dir(repo_path, ext=".repo")
68
69 def get_repos(self):
70 repos = []
71
72 for name, settings in self._config.items():
73 if not name.startswith("repo:"):
74 continue
75
76 # Strip "repo:" from name of the repository.
77 name = name[5:]
78
79 repos.append((name, settings))
80
81 return repos
82
83 def read_dir(self, where, ext=".conf"):
84 for file in os.listdir(where):
85 if not file.endswith(ext):
86 continue
87
88 file = os.path.join(where, file)
89 self.read(file)
90
91 def read(self, *files):
92 # Do nothing for no files.
93 if not files:
94 return
95
96 for file in files:
97 if not file.startswith("/"):
98 file = os.path.join(CONFIG_DIR, file)
99
100 if not os.path.exists(file):
101 continue
102
103 # Normalize filename.
104 file = os.path.abspath(file)
105
106 # Check if file has already been read or
107 # does not exist. Then skip it.
108 if file in self._files or not os.path.exists(file):
109 continue
110
111 # Parse the file.
112 with open(file) as f:
113 self.parse(f.read())
114
115 # Save the filename to the list of read files.
116 self._files.append(file)
117
118 def parse(self, s):
119 if not s:
120 return
121
122 buf = io.BytesIO(s)
123
124 config = ConfigParser()
125 config.readfp(buf)
126
127 # Read all data from the configuration file in the _config dict.
128 for section in config.sections():
129 items = dict(config.items(section))
130
131 if section == "DEFAULT":
132 section = "main"
133
134 try:
135 self._config[section].update(items)
136 except KeyError:
137 self._config[section] = items
138
139 # Update the logger, because the logging configuration may
140 # have been altered.
141 logger.setup_logging(self)
142
143 def set(self, section, key, value):
144 try:
145 self._config[section][key] = value
146 except KeyError:
147 self._config[section] = { key : value }
148
149 def get_section(self, section):
150 try:
151 return self._config[section]
152 except KeyError:
153 return {}
154
155 def get(self, section, key, default=None):
156 s = self.get_section(section)
157
158 try:
159 return s[key]
160 except KeyError:
161 return default
162
163 def get_int(self, section, key, default=None):
164 val = self.get(section=section, key=key, default=default)
165 try:
166 val = int(val)
167 except ValueError:
168 return default
169
170 def get_bool(self, section, key, default=None):
171 val = self.get(section=section, key=key, default=default)
172
173 if val in (True, "true", "1", "on"):
174 return True
175 elif val in (False, "false", "0", "off"):
176 return False
177
178 return default
179
180 def update(self, section, what):
181 try:
182 self._config[section].update(what)
183 except KeyError:
184 self._config[section] = what
185
186 def dump(self):
187 """
188 Dump the configuration that was read.
189
190 (Only in debugging mode.)
191 """
192 log.debug(_("Configuration:"))
193 for section, settings in self._config.items():
194 log.debug(" " + _("Section: %s") % section)
195
196 for k, v in settings.items():
197 log.debug(" %-20s: %s" % (k, v))
198 else:
199 log.debug(" " + _("No settings in this section."))
200
201 log.debug(" " + _("Loaded from files:"))
202 for f in self._files:
203 log.debug(" %s" % f)
204
205
206 class Config(_Config):
207 files = ["general.conf"]
208
209
210 class ConfigBuilder(_Config):
211 files = ["general.conf", "builder.conf", "default.conf"]
212
213
214 class ConfigClient(_Config):
215 files = ["general.conf", "client.conf"]
216
217 default_settings = {
218 "client" : {
219 # The default server is the official Pakfire
220 # server.
221 "server" : "https://pakfire.ipfire.org",
222 },
223 }
224
225
226 class ConfigDaemon(_Config):
227 files = ["general.conf", "daemon.conf"]
228
229 default_settings = {
230 "daemon" : {
231 # The default server is the official Pakfire
232 # server.
233 "server" : "https://pakfire.ipfire.org",
234
235 # The default hostname is the host name of this
236 # machine.
237 "hostname" : system.hostname,
238 },
239 }