# 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""" import abc from functools import wraps import inspect import logging import os import re from collections import OrderedDict from git.compat import ( string_types, FileType, defenc, force_text, with_metaclass, PY3 ) from git.util import LockFile import os.path as osp try: import ConfigParser as cp except ImportError: # PY3 import configparser as cp __all__ = ('GitConfigParser', 'SectionConstraint') log = logging.getLogger('git.config') log.addHandler(logging.NullHandler()) class MetaParserBuilder(abc.ABCMeta): """Utlity class wrapping base-class methods into decorators that assure read-only properties""" def __new__(cls, 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_' if kmm in clsdict: mutating_methods = clsdict[kmm] for base in bases: methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_")) for name, method in methods: if name in clsdict: continue method_with_values = needs_values(method) if name in mutating_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, cls).__new__(cls, name, bases, clsdict) return new_type def needs_values(func): """Returns method assuring we read values (on demand) before we try to access them""" @wraps(func) def assure_data_present(self, *args, **kwargs): self.read() return func(self, *args, **kwargs) # END wrapper method return assure_data_present def set_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""" def flush_changes(self, *args, **kwargs): rval = non_const_func(self, *args, **kwargs) self._dirty = True self.write() return rval # END wrapper method flush_changes.__name__ = non_const_func.__name__ return flush_changes 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. :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") def __init__(self, config, section): self._config = config self._section_name = section def __del__(self): # Yes, for some reason, we have to call it explicitly for it to work in PY3 ! # Apparently __del__ doesn't get call anymore if refcount becomes 0 # Ridiculous ... . self._config.release() def __getattr__(self, attr): if attr in self._valid_attrs_: return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs) return super(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""" return getattr(self._config, method)(self._section_name, *args, **kwargs) @property def config(self): """return: Configparser instance we constrain""" return self._config def release(self): """Equivalent to GitConfigParser.release(), which is called on our underlying parser instance""" return self._config.release() def __enter__(self): self._config.__enter__() return self def __exit__(self, exception_type, exception_value, traceback): self._config.__exit__(exception_type, exception_value, traceback) class _OMD(OrderedDict): """Ordered multi-dict.""" def __setitem__(self, key, value): super(_OMD, self).__setitem__(key, [value]) def add(self, key, value): if key not in self: super(_OMD, self).__setitem__(key, [value]) return super(_OMD, self).__getitem__(key).append(value) def setall(self, key, values): super(_OMD, self).__setitem__(key, values) def __getitem__(self, key): return super(_OMD, self).__getitem__(key)[-1] def getlast(self, key): return super(_OMD, self).__getitem__(key)[-1] def setlast(self, key, value): if key not in self: super(_OMD, self).__setitem__(key, [value]) return prior = super(_OMD, self).__getitem__(key) prior[-1] = value def get(self, key, default=None): return super(_OMD, self).get(key, [default])[-1] def getall(self, key): return super(_OMD, self).__getitem__(key) def items(self): """List of (key, last value for key).""" return [(k, self[k]) for k in self] def items_all(self): """List of (key, list of values for key).""" return [(k, self.getall(k)) for k in self] class GitConfigParser(with_metaclass(MetaParserBuilder, 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. If used as a context manager, will release the locked file.""" #{ 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(r'^\s*[#;]') #} END configuration optvalueonly_source = r'\s*(?P