Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork966
Expand file tree
/
Copy pathconfig.py
More file actions
462 lines (385 loc) · 17.7 KB
/
config.py
File metadata and controls
462 lines (385 loc) · 17.7 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# config.py
# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
#
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
"""Module containing module parser implementation able to properly read and write
configuration files"""
importre
importos
importConfigParserascp
importinspect
importcStringIO
fromgit.odictimportOrderedDict
fromgit.utilimportLockFile
__all__= ('GitConfigParser','SectionConstraint')
classMetaParserBuilder(type):
"""Utlity class wrapping base-class methods into decorators that assure read-only properties"""
def__new__(metacls,name,bases,clsdict):
"""
Equip all base-class methods with a needs_values decorator, and all non-const methods
with a set_dirty_and_flush_changes decorator in addition to that."""
kmm='_mutating_methods_'
ifkmminclsdict:
mutating_methods=clsdict[kmm]
forbaseinbases:
methods= (tfortininspect.getmembers(base,inspect.ismethod)ifnott[0].startswith("_"))
forname,methodinmethods:
ifnameinclsdict:
continue
method_with_values=needs_values(method)
ifnameinmutating_methods:
method_with_values=set_dirty_and_flush_changes(method_with_values)
# END mutating methods handling
clsdict[name]=method_with_values
# END for each name/method pair
# END for each base
# END if mutating methods configuration is set
new_type=super(MetaParserBuilder,metacls).__new__(metacls,name,bases,clsdict)
returnnew_type
defneeds_values(func):
"""Returns method assuring we read values (on demand) before we try to access them"""
defassure_data_present(self,*args,**kwargs):
self.read()
returnfunc(self,*args,**kwargs)
# END wrapper method
assure_data_present.__name__=func.__name__
returnassure_data_present
defset_dirty_and_flush_changes(non_const_func):
"""Return method that checks whether given non constant function may be called.
If so, the instance will be set dirty.
Additionally, we flush the changes right to disk"""
defflush_changes(self,*args,**kwargs):
rval=non_const_func(self,*args,**kwargs)
self.write()
returnrval
# END wrapper method
flush_changes.__name__=non_const_func.__name__
returnflush_changes
classSectionConstraint(object):
"""Constrains a ConfigParser to only option commands which are constrained to
always use the section we have been initialized with.
It supports all ConfigParser methods that operate on an option"""
__slots__= ("_config","_section_name")
_valid_attrs_= ("get_value","set_value","get","set","getint","getfloat","getboolean","has_option",
"remove_section","remove_option","options")
def__init__(self,config,section):
self._config=config
self._section_name=section
def__getattr__(self,attr):
ifattrinself._valid_attrs_:
returnlambda*args,**kwargs:self._call_config(attr,*args,**kwargs)
returnsuper(SectionConstraint,self).__getattribute__(attr)
def_call_config(self,method,*args,**kwargs):
"""Call the configuration at the given method which must take a section name
as first argument"""
returngetattr(self._config,method)(self._section_name,*args,**kwargs)
@property
defconfig(self):
"""return: Configparser instance we constrain"""
returnself._config
classGitConfigParser(cp.RawConfigParser,object):
"""Implements specifics required to read git style configuration files.
This variation behaves much like the git.config command such that the configuration
will be read on demand based on the filepath given during initialization.
The changes will automatically be written once the instance goes out of scope, but
can be triggered manually as well.
The configuration file will be locked if you intend to change values preventing other
instances to write concurrently.
:note:
The config is case-sensitive even when queried, hence section and option names
must match perfectly."""
__metaclass__=MetaParserBuilder
#{ Configuration
# The lock type determines the type of lock to use in new configuration readers.
# They must be compatible to the LockFile interface.
# A suitable alternative would be the BlockingLockFile
t_lock=LockFile
re_comment=re.compile('^\s*[#;]')
#} END configuration
OPTCRE=re.compile(
r'\s*(?P<option>[^:=\s][^:=]*)'# very permissive, incuding leading whitespace
r'\s*(?:'# any number of space/tab,
r'(?P<vi>[:=])\s*'# optionally followed by
# separator (either : or
# =), followed by any #
# space/tab
r'(?P<value>.*))?$'# everything up to eol
)
# list of RawConfigParser methods able to change the instance
_mutating_methods_= ("add_section","remove_section","remove_option","set")
__slots__= ("_sections","_defaults","_file_or_files","_read_only","_is_initialized",'_lock')
def__init__(self,file_or_files,read_only=True):
"""Initialize a configuration reader to read the given file_or_files and to
possibly allow changes to it by setting read_only False
:param file_or_files:
A single file path or file objects or multiple of these
:param read_only:
If True, the ConfigParser may only read the data , but not change it.
If False, only a single file path or file object may be given."""
super(GitConfigParser,self).__init__()
# initialize base with ordered dictionaries to be sure we write the same
# file back
self._sections=OrderedDict()
self._defaults=OrderedDict()
self._file_or_files=file_or_files
self._read_only=read_only
self._is_initialized=False
self._lock=None
ifnotread_only:
ifisinstance(file_or_files, (tuple,list)):
raiseValueError(
"Write-ConfigParsers can operate on a single file only, multiple files have been passed")
# END single file check
ifnotisinstance(file_or_files,basestring):
file_or_files=file_or_files.name
# END get filename from handle/stream
# initialize lock base - we want to write
self._lock=self.t_lock(file_or_files)
self._lock._obtain_lock()
# END read-only check
def__del__(self):
"""Write pending changes if required and release locks"""
# checking for the lock here makes sure we do not raise during write()
# in case an invalid parser was created who could not get a lock
ifself.read_onlyornotself._lock._has_lock():
return
try:
try:
self.write()
exceptIOError,e:
print"Exception during destruction of GitConfigParser: %s"%str(e)
finally:
self._lock._release_lock()
defoptionxform(self,optionstr):
"""Do not transform options in any way when writing"""
returnoptionstr
def_read(self,fp,fpname):
"""A direct copy of the py2.7 version of the super class's _read method
to assure it uses ordered dicts. Had to change one line to make it work.
Future versions have this fixed, but in fact its quite embarassing for the
guys not to have done it right in the first place !
Removed big comments to make it more compact.
Made sure it ignores initial whitespace as git uses tabs"""
cursect=None# None, or a dictionary
optname=None
lineno=0
e=None# None, or an exception
whileTrue:
line=fp.readline()
ifnotline:
break
lineno=lineno+1
# comment or blank line?
ifline.strip()==''orself.re_comment.match(line):
continue
ifline.split(None,1)[0].lower()=='rem'andline[0]in"rR":
# no leading whitespace
continue
# a section header or option header?
else:
# is it a section header?
mo=self.SECTCRE.match(line.strip())
ifmo:
sectname=mo.group('header').strip()
ifsectnameinself._sections:
cursect=self._sections[sectname]
elifsectname==cp.DEFAULTSECT:
cursect=self._defaults
else:
# THE ONLY LINE WE CHANGED !
cursect=OrderedDict((('__name__',sectname),))
self._sections[sectname]=cursect
# So sections can't start with a continuation line
optname=None
# no section header in the file?
elifcursectisNone:
raisecp.MissingSectionHeaderError(fpname,lineno,line)
# an option line?
else:
mo=self.OPTCRE.match(line)
ifmo:
optname,vi,optval=mo.group('option','vi','value')
optname=self.optionxform(optname.rstrip())
ifoptvalisnotNone:
ifviin ('=',':')and';'inoptval:
# ';' is a comment delimiter only if it follows
# a spacing character
pos=optval.find(';')
ifpos!=-1andoptval[pos-1].isspace():
optval=optval[:pos]
optval=optval.strip()
# allow empty values
ifoptval=='""':
optval=''
# Remove paired unescaped-quotes
unquoted_optval=''
escaped=False
in_quote=False
forcinoptval:
ifnotescapedandc=='"':
in_quote=notin_quote
else:
escaped= (c=='\\')andnotescaped
unquoted_optval+=c
ifin_quote:
ifnote:
e=cp.ParsingError(fpname)
e.append(lineno,repr(line))
optval=unquoted_optval
optval=optval.replace('\\\\','\\')# Unescape backslashes
optval=optval.replace(r'\"','"')# Unescape quotes
cursect[optname]=optval
else:
# valueless option handling
cursect[optname]=optval
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
ifnote:
e=cp.ParsingError(fpname)
e.append(lineno,repr(line))
# if any parsing errors occurred, raise an exception
ife:
raisee
defread(self):
"""Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled"""
ifself._is_initialized:
return
files_to_read=self._file_or_files
ifnotisinstance(files_to_read, (tuple,list)):
files_to_read= [files_to_read]
forfile_objectinfiles_to_read:
fp=file_object
close_fp=False
# assume a path if it is not a file-object
ifnothasattr(file_object,"seek"):
try:
fp=open(file_object)
close_fp=True
exceptIOError,e:
continue
# END fp handling
try:
self._read(fp,fp.name)
finally:
ifclose_fp:
fp.close()
# END read-handling
# END for each file object to read
self._is_initialized=True
def_write(self,fp):
"""Write an .ini-format representation of the configuration state in
git compatible format"""
defwrite_section(name,section_dict):
fp.write("[%s]\n"%name)
for (key,value)insection_dict.items():
ifkey!="__name__":
value=str(value)
value=value.replace('\\','\\\\')# Escape backslashes
value=value.replace('"',r'\"')# Escape quotes
value=value.replace('\n','\n\t')
fp.write("\t%s = %s\n"% (key,value))
# END if key is not __name__
# END section writing
ifself._defaults:
write_section(cp.DEFAULTSECT,self._defaults)
map(lambdat:write_section(t[0],t[1]),self._sections.items())
@needs_values
defwrite(self):
"""Write changes to our file, if there are changes at all
:raise IOError: if this is a read-only writer instance or if we could not obtain
a file lock"""
self._assure_writable("write")
fp=self._file_or_files
close_fp=False
# we have a physical file on disk, so get a lock
ifisinstance(fp, (basestring,file)):
self._lock._obtain_lock()
# END get lock for physical files
ifnothasattr(fp,"seek"):
fp=open(self._file_or_files,"w")
close_fp=True
else:
fp.seek(0)
# make sure we do not overwrite into an existing file
ifhasattr(fp,'truncate'):
fp.truncate()
# END
# END handle stream or file
# WRITE DATA
try:
self._write(fp)
finally:
ifclose_fp:
fp.close()
# END data writing
# we do not release the lock - it will be done automatically once the
# instance vanishes
def_assure_writable(self,method_name):
ifself.read_only:
raiseIOError("Cannot execute non-constant method %s.%s"% (self,method_name))
@needs_values
@set_dirty_and_flush_changes
defadd_section(self,section):
"""Assures added options will stay in order"""
super(GitConfigParser,self).add_section(section)
self._sections[section]=OrderedDict()
@property
defread_only(self):
""":return: True if this instance may change the configuration file"""
returnself._read_only
defget_value(self,section,option,default=None):
"""
:param default:
If not None, the given default value will be returned in case
the option did not exist
:return: a properly typed value, either int, bool, float, string or None
:raise TypeError: in case the value could not be understood
Otherwise the exceptions known to the ConfigParser will be raised."""
try:
valuestr=self.get(section,option)
exceptException:
ifdefaultisnotNone:
returndefault
raise
ifvaluestrisNone:
returnvaluestr
types= (long,float)
fornumtypeintypes:
try:
val=numtype(valuestr)
# truncated value ?
ifval!=float(valuestr):
continue
returnval
except (ValueError,TypeError):
continue
# END for each numeric type
# try boolean values as git uses them
vl=valuestr.lower()
ifvl=='false':
returnFalse
ifvl=='true':
returnTrue
ifnotisinstance(valuestr,basestring):
raiseTypeError("Invalid value type: only int, long, float and str are allowed",valuestr)
returnvaluestr
@needs_values
@set_dirty_and_flush_changes
defset_value(self,section,option,value):
"""Sets the given option in section to the given value.
It will create the section if required, and will not throw as opposed to the default
ConfigParser 'set' method.
:param section: Name of the section in which the option resides or should reside
:param option: Name of the options whose value to set
:param value: Value to set the option to. It must be a string or convertible
to a string"""
ifnotself.has_section(section):
self.add_section(section)
self.set(section,option,str(value))