Skip to content

Commit 7d00fa4

Browse files
committed
config: implemented get_value method to have a safe way to make general queries to the git configuration, returning a value in the proper type. In a way its not supposed to be used as you should know the type of your configuration option or get an exception otherwise
1 parent c05ef0e commit 7d00fa4

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/git/config.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,3 +346,36 @@ def read_only(self):
346346
True if this instance may change the configuration file
347347
"""
348348
return self._read_only
349+
350+
def get_value(self, section, option):
351+
"""
352+
Returns
353+
a properly typed value, either int, float or string
354+
Raises TypeError in case the value could not be understood
355+
"""
356+
valuestr = self.get(section, option)
357+
types = ( long, float )
358+
for numtype in types:
359+
try:
360+
val = numtype( valuestr )
361+
362+
# truncated value ?
363+
if val != float( valuestr ):
364+
continue
365+
366+
return val
367+
except (ValueError,TypeError):
368+
continue
369+
# END for each numeric type
370+
371+
# try boolean values as git uses them
372+
vl = valuestr.lower()
373+
if vl == 'false':
374+
return False
375+
if vl == 'true':
376+
return True
377+
378+
if not isinstance( valuestr, basestring ):
379+
raise TypeError( "Invalid value type: only int, long, float and str are allowed", valuestr )
380+
381+
return valuestr

test/git/test_config.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ def test_base(self):
7272
for option in r_config.options(section):
7373
num_options += 1
7474
val = r_config.get(section, option)
75+
val_typed = r_config.get_value(section, option)
76+
assert isinstance(val_typed, (bool, long, float, basestring))
7577
assert val
7678
assert "\n" not in option
7779
assert "\n" not in val

0 commit comments

Comments
 (0)