summaryrefslogtreecommitdiff
path: root/git/config.py
diff options
context:
space:
mode:
authorRaphael Boidol <raphael.boidol@tngtech.com>2016-02-20 22:00:59 +0100
committerRaphael Boidol <raphael.boidol@tngtech.com>2016-02-20 22:09:31 +0100
commitdc9278fb4432f0244f4d780621d5c1b57a03b720 (patch)
tree56c604bd90d2d39b5849904161aa5e29ed1c2a07 /git/config.py
parent121f6af3a75e4f48acf31b1af2386cdd5bf91e00 (diff)
downloadgitpython-dc9278fb4432f0244f4d780621d5c1b57a03b720.tar.gz
enable config parsers to be used as context managers
if used as context managers, the parsers will automatically release their file locks.
Diffstat (limited to 'git/config.py')
-rw-r--r--git/config.py21
1 files changed, 19 insertions, 2 deletions
diff --git a/git/config.py b/git/config.py
index 51b15989..21af6159 100644
--- a/git/config.py
+++ b/git/config.py
@@ -95,7 +95,10 @@ class SectionConstraint(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"""
+ It supports all ConfigParser methods that operate on an option.
+
+ :note:
+ If used as a context manager, will release the wrapped ConfigParser."""
__slots__ = ("_config", "_section_name")
_valid_attrs_ = ("get_value", "set_value", "get", "set", "getint", "getfloat", "getboolean", "has_option",
"remove_section", "remove_option", "options")
@@ -129,6 +132,12 @@ class SectionConstraint(object):
"""Equivalent to GitConfigParser.release(), which is called on our underlying parser instance"""
return self._config.release()
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exception_type, exception_value, traceback):
+ self.release()
+
class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, object)):
@@ -145,7 +154,9 @@ class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, obje
:note:
The config is case-sensitive even when queried, hence section and option names
- must match perfectly."""
+ must match perfectly.
+ If used as a context manager, will release the locked file. This parser cannot
+ be used afterwards."""
#{ Configuration
# The lock type determines the type of lock to use in new configuration readers.
@@ -216,6 +227,12 @@ class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, obje
# NOTE: only consistent in PY2
self.release()
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exception_type, exception_value, traceback):
+ self.release()
+
def release(self):
"""Flush changes and release the configuration write lock. This instance must not be used anymore afterwards.
In Python 3, it's required to explicitly release locks and flush changes, as __del__ is not called