Debian Codegraph @

xdg/IniFile.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Base Class for DesktopEntry, IconTheme and IconData
3 """
4
5 import re, os, stat, io
6 from xdg.Exceptions import (ParsingError, DuplicateGroupError, NoGroupError,
7 NoKeyError, DuplicateKeyError, ValidationError,
8 debug)
9 import xdg.Locale
10 from xdg.util import u
•11 import gettext
12
13 def is_ascii(s):
14 """Return True if a string consists entirely of ASCII characters."""
15 try:
16 s.encode('ascii', 'strict')
17 return True
18 except UnicodeError:
19 return False
20
21 class IniFile:
22 defaultGroup = ''
23 fileExtension = ''
24
25 filename = ''
•26 gettext_domain = None
27
28 tainted = False
29
30 def __init__(self, filename=None):
31 self.content = dict()
32 if filename:
33 self.parse(filename)
34
35 def __cmp__(self, other):
36 return cmp(self.content, other.content)
37
38 def parse(self, filename, headers=None):
39 '''Parse an INI file.
40
41 headers -- list of headers the parser will try to select as a default header
42 '''
43 # for performance reasons
44 content = self.content
45
46 if not os.path.isfile(filename):
47 raise ParsingError("File not found", filename)
48
49 try:
50 # The content should be UTF-8, but legacy files can have other
51 # encodings, including mixed encodings in one file. We don't attempt
52 # to decode them, but we silence the errors.
53 fd = io.open(filename, 'r', encoding='utf-8', errors='replace')
54 except IOError as e:
55 if debug:
56 raise e
57 else:
58 return
59
60 # parse file
61 with fd:
62 for line in fd:
63 line = line.strip()
64 # empty line
65 if not line:
66 continue
67 # comment
68 elif line[0] == '#':
69 continue
70 # new group
71 elif line[0] == '[':
72 currentGroup = line.lstrip("[").rstrip("]")
73 if debug and self.hasGroup(currentGroup):
74 raise DuplicateGroupError(currentGroup, filename)
75 else:
76 content[currentGroup] = {}
77 # key
78 else:
79 try:
80 key, value = line.split("=", 1)
81 except ValueError:
82 raise ParsingError("Invalid line: " + line, filename)
83
84 key = key.strip() # Spaces before/after '=' should be ignored
85 try:
86 if debug and self.hasKey(key, currentGroup):
87 raise DuplicateKeyError(key, currentGroup, filename)
88 else:
89 content[currentGroup][key] = value.strip()
90 except (IndexError, UnboundLocalError):
91 raise ParsingError("Parsing error on key, group missing", filename)
92
93 self.filename = filename
94 self.tainted = False
95
96 # check header
97 if headers:
98 for header in headers:
99 if header in content:
100 self.defaultGroup = header
101 break
102 else:
103 raise ParsingError("[%s]-Header missing" % headers[0], filename)
104
•105 # check for gettext domain
106 e = self.content.get('Desktop Entry', {})
107 self.gettext_domain = e.get('X-GNOME-Gettext-Domain',
108 e.get('X-Ubuntu-Gettext-Domain', None))
109
110 # start stuff to access the keys
111 def get(self, key, group=None, locale=False, type="string", list=False, strict=False):
112 # set default group
113 if not group:
114 group = self.defaultGroup
115
116 # return key (with locale)
117 if (group in self.content) and (key in self.content[group]):
118 if locale:
•119 key = self.__addLocale(key, group)
120 if key.endswith(']') or not self.gettext_domain:
121 # inline translations
122 value = self.content[group][key]
123 else:
124 value = gettext.dgettext(self.gettext_domain, self.content[group][key])
125 else:
126 value = self.content[group][key]
127 else:
128 if strict or debug:
129 if group not in self.content:
130 raise NoGroupError(group, self.filename)
131 elif key not in self.content[group]:
132 raise NoKeyError(key, group, self.filename)
133 else:
134 value = ""
135
136 if list == True:
137 values = self.getList(value)
138 result = []
139 else:
140 values = [value]
141
142 for value in values:
143 if type == "boolean":
144 value = self.__getBoolean(value)
145 elif type == "integer":
146 try:
147 value = int(value)
148 except ValueError:
149 value = 0
150 elif type == "numeric":
151 try:
152 value = float(value)
153 except ValueError:
154 value = 0.0
155 elif type == "regex":
156 value = re.compile(value)
157 elif type == "point":
158 x, y = value.split(",")
159 value = int(x), int(y)
160
161 if list == True:
162 result.append(value)
163 else:
164 result = value
165
166 return result
167 # end stuff to access the keys
168
169 # start subget
170 def getList(self, string):
171 if re.search(r"(?<!\\)\;", string):
172 list = re.split(r"(?<!\\);", string)
173 elif re.search(r"(?<!\\)\|", string):
174 list = re.split(r"(?<!\\)\|", string)
175 elif re.search(r"(?<!\\),", string):
176 list = re.split(r"(?<!\\),", string)
177 else:
178 list = [string]
179 if list[-1] == "":
180 list.pop()
181 return list
182
183 def __getBoolean(self, boolean):
184 if boolean == 1 or boolean == "true" or boolean == "True":
185 return True
186 elif boolean == 0 or boolean == "false" or boolean == "False":
187 return False
188 return False
189 # end subget
190
191 def __addLocale(self, key, group=None):
192 "add locale to key according the current lc_messages"
193 # set default group
194 if not group:
195 group = self.defaultGroup
196
197 for lang in xdg.Locale.langs:
198 langkey = "%s[%s]" % (key, lang)
199 if langkey in self.content[group]:
200 return langkey
201
202 return key
203
204 # start validation stuff
205 def validate(self, report="All"):
206 """Validate the contents, raising :class:`~xdg.Exceptions.ValidationError`
207 if there is anything amiss.
208
209 report can be 'All' / 'Warnings' / 'Errors'
210 """
211
212 self.warnings = []
213 self.errors = []
214
215 # get file extension
216 self.fileExtension = os.path.splitext(self.filename)[1]
217
218 # overwrite this for own checkings
219 self.checkExtras()
220
221 # check all keys
222 for group in self.content:
223 self.checkGroup(group)
224 for key in self.content[group]:
225 self.checkKey(key, self.content[group][key], group)
226 # check if value is empty
227 if self.content[group][key] == "":
228 self.warnings.append("Value of Key '%s' is empty" % key)
229
230 # raise Warnings / Errors
231 msg = ""
232
233 if report == "All" or report == "Warnings":
234 for line in self.warnings:
235 msg += "\n- " + line
236
237 if report == "All" or report == "Errors":
238 for line in self.errors:
239 msg += "\n- " + line
240
241 if msg:
242 raise ValidationError(msg, self.filename)
243
244 # check if group header is valid
245 def checkGroup(self, group):
246 pass
247
248 # check if key is valid
249 def checkKey(self, key, value, group):
250 pass
251
252 # check random stuff
253 def checkValue(self, key, value, type="string", list=False):
254 if list == True:
255 values = self.getList(value)
256 else:
257 values = [value]
258
259 for value in values:
260 if type == "string":
261 code = self.checkString(value)
262 if type == "localestring":
263 continue
264 elif type == "boolean":
265 code = self.checkBoolean(value)
266 elif type == "numeric":
267 code = self.checkNumber(value)
268 elif type == "integer":
269 code = self.checkInteger(value)
270 elif type == "regex":
271 code = self.checkRegex(value)
272 elif type == "point":
273 code = self.checkPoint(value)
274 if code == 1:
275 self.errors.append("'%s' is not a valid %s" % (value, type))
276 elif code == 2:
277 self.warnings.append("Value of key '%s' is deprecated" % key)
278
279 def checkExtras(self):
280 pass
281
282 def checkBoolean(self, value):
283 # 1 or 0 : deprecated
284 if (value == "1" or value == "0"):
285 return 2
286 # true or false: ok
287 elif not (value == "true" or value == "false"):
288 return 1
289
290 def checkNumber(self, value):
291 # float() ValueError
292 try:
293 float(value)
294 except:
295 return 1
296
297 def checkInteger(self, value):
298 # int() ValueError
299 try:
300 int(value)
301 except:
302 return 1
303
304 def checkPoint(self, value):
305 if not re.match("^[0-9]+,[0-9]+$", value):
306 return 1
307
308 def checkString(self, value):
309 return 0 if is_ascii(value) else 1
310
311 def checkRegex(self, value):
312 try:
313 re.compile(value)
314 except:
315 return 1
316
317 # write support
318 def write(self, filename=None, trusted=False):
319 if not filename and not self.filename:
320 raise ParsingError("File not found", "")
321
322 if filename:
323 self.filename = filename
324 else:
325 filename = self.filename
326
327 if os.path.dirname(filename) and not os.path.isdir(os.path.dirname(filename)):
328 os.makedirs(os.path.dirname(filename))
329
330 with io.open(filename, 'w', encoding='utf-8') as fp:
331
332 # An executable bit signifies that the desktop file is
333 # trusted, but then the file can be executed. Add hashbang to
334 # make sure that the file is opened by something that
335 # understands desktop files.
336 if trusted:
337 fp.write(u("#!/usr/bin/env xdg-open\n"))
338
339 if self.defaultGroup:
340 fp.write(u("[%s]\n") % self.defaultGroup)
341 for (key, value) in self.content[self.defaultGroup].items():
342 fp.write(u("%s=%s\n") % (key, value))
343 fp.write(u("\n"))
344 for (name, group) in self.content.items():
345 if name != self.defaultGroup:
346 fp.write(u("[%s]\n") % name)
347 for (key, value) in group.items():
348 fp.write(u("%s=%s\n") % (key, value))
349 fp.write(u("\n"))
350
351 # Add executable bits to the file to show that it's trusted.
352 if trusted:
353 oldmode = os.stat(filename).st_mode
354 mode = oldmode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
355 os.chmod(filename, mode)
356
357 self.tainted = False
358
359 def set(self, key, value, group=None, locale=False):
360 # set default group
361 if not group:
362 group = self.defaultGroup
363
364 if locale == True and len(xdg.Locale.langs) > 0:
365 key = key + "[" + xdg.Locale.langs[0] + "]"
366
367 try:
368 self.content[group][key] = value
369 except KeyError:
370 raise NoGroupError(group, self.filename)
371
372 self.tainted = (value == self.get(key, group))
373
374 def addGroup(self, group):
375 if self.hasGroup(group):
376 if debug:
377 raise DuplicateGroupError(group, self.filename)
378 else:
379 self.content[group] = {}
380 self.tainted = True
381
382 def removeGroup(self, group):
383 existed = group in self.content
384 if existed:
385 del self.content[group]
386 self.tainted = True
387 else:
388 if debug:
389 raise NoGroupError(group, self.filename)
390 return existed
391
392 def removeKey(self, key, group=None, locales=True):
393 # set default group
394 if not group:
395 group = self.defaultGroup
396
397 try:
398 if locales:
399 for name in list(self.content[group]):
400 if re.match("^" + key + xdg.Locale.regex + "$", name) and name != key:
401 del self.content[group][name]
402 value = self.content[group].pop(key)
403 self.tainted = True
404 return value
405 except KeyError as e:
406 if debug:
407 if e == group:
408 raise NoGroupError(group, self.filename)
409 else:
410 raise NoKeyError(key, group, self.filename)
411 else:
412 return ""
413
414 # misc
415 def groups(self):
416 return self.content.keys()
417
418 def hasGroup(self, group):
419 return group in self.content
420
421 def hasKey(self, key, group=None):
422 # set default group
423 if not group:
424 group = self.defaultGroup
425
426 return key in self.content[group]
427
428 def getFileName(self):
429 return self.filename