You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

711 lines
26KB

  1. # config.py
  2. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  3. #
  4. # This module is part of GitPython and is released under
  5. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  6. """Module containing module parser implementation able to properly read and write
  7. configuration files"""
  8. import abc
  9. from functools import wraps
  10. import inspect
  11. import logging
  12. import os
  13. import re
  14. from collections import OrderedDict
  15. from git.compat import (
  16. string_types,
  17. FileType,
  18. defenc,
  19. force_text,
  20. with_metaclass,
  21. PY3
  22. )
  23. from git.util import LockFile
  24. import os.path as osp
  25. try:
  26. import ConfigParser as cp
  27. except ImportError:
  28. # PY3
  29. import configparser as cp
  30. __all__ = ('GitConfigParser', 'SectionConstraint')
  31. log = logging.getLogger('git.config')
  32. log.addHandler(logging.NullHandler())
  33. class MetaParserBuilder(abc.ABCMeta):
  34. """Utlity class wrapping base-class methods into decorators that assure read-only properties"""
  35. def __new__(cls, name, bases, clsdict):
  36. """
  37. Equip all base-class methods with a needs_values decorator, and all non-const methods
  38. with a set_dirty_and_flush_changes decorator in addition to that."""
  39. kmm = '_mutating_methods_'
  40. if kmm in clsdict:
  41. mutating_methods = clsdict[kmm]
  42. for base in bases:
  43. methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_"))
  44. for name, method in methods:
  45. if name in clsdict:
  46. continue
  47. method_with_values = needs_values(method)
  48. if name in mutating_methods:
  49. method_with_values = set_dirty_and_flush_changes(method_with_values)
  50. # END mutating methods handling
  51. clsdict[name] = method_with_values
  52. # END for each name/method pair
  53. # END for each base
  54. # END if mutating methods configuration is set
  55. new_type = super(MetaParserBuilder, cls).__new__(cls, name, bases, clsdict)
  56. return new_type
  57. def needs_values(func):
  58. """Returns method assuring we read values (on demand) before we try to access them"""
  59. @wraps(func)
  60. def assure_data_present(self, *args, **kwargs):
  61. self.read()
  62. return func(self, *args, **kwargs)
  63. # END wrapper method
  64. return assure_data_present
  65. def set_dirty_and_flush_changes(non_const_func):
  66. """Return method that checks whether given non constant function may be called.
  67. If so, the instance will be set dirty.
  68. Additionally, we flush the changes right to disk"""
  69. def flush_changes(self, *args, **kwargs):
  70. rval = non_const_func(self, *args, **kwargs)
  71. self._dirty = True
  72. self.write()
  73. return rval
  74. # END wrapper method
  75. flush_changes.__name__ = non_const_func.__name__
  76. return flush_changes
  77. class SectionConstraint(object):
  78. """Constrains a ConfigParser to only option commands which are constrained to
  79. always use the section we have been initialized with.
  80. It supports all ConfigParser methods that operate on an option.
  81. :note:
  82. If used as a context manager, will release the wrapped ConfigParser."""
  83. __slots__ = ("_config", "_section_name")
  84. _valid_attrs_ = ("get_value", "set_value", "get", "set", "getint", "getfloat", "getboolean", "has_option",
  85. "remove_section", "remove_option", "options")
  86. def __init__(self, config, section):
  87. self._config = config
  88. self._section_name = section
  89. def __del__(self):
  90. # Yes, for some reason, we have to call it explicitly for it to work in PY3 !
  91. # Apparently __del__ doesn't get call anymore if refcount becomes 0
  92. # Ridiculous ... .
  93. self._config.release()
  94. def __getattr__(self, attr):
  95. if attr in self._valid_attrs_:
  96. return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs)
  97. return super(SectionConstraint, self).__getattribute__(attr)
  98. def _call_config(self, method, *args, **kwargs):
  99. """Call the configuration at the given method which must take a section name
  100. as first argument"""
  101. return getattr(self._config, method)(self._section_name, *args, **kwargs)
  102. @property
  103. def config(self):
  104. """return: Configparser instance we constrain"""
  105. return self._config
  106. def release(self):
  107. """Equivalent to GitConfigParser.release(), which is called on our underlying parser instance"""
  108. return self._config.release()
  109. def __enter__(self):
  110. self._config.__enter__()
  111. return self
  112. def __exit__(self, exception_type, exception_value, traceback):
  113. self._config.__exit__(exception_type, exception_value, traceback)
  114. class _OMD(OrderedDict):
  115. """Ordered multi-dict."""
  116. def __setitem__(self, key, value):
  117. super(_OMD, self).__setitem__(key, [value])
  118. def add(self, key, value):
  119. if key not in self:
  120. super(_OMD, self).__setitem__(key, [value])
  121. return
  122. super(_OMD, self).__getitem__(key).append(value)
  123. def setall(self, key, values):
  124. super(_OMD, self).__setitem__(key, values)
  125. def __getitem__(self, key):
  126. return super(_OMD, self).__getitem__(key)[-1]
  127. def getlast(self, key):
  128. return super(_OMD, self).__getitem__(key)[-1]
  129. def setlast(self, key, value):
  130. if key not in self:
  131. super(_OMD, self).__setitem__(key, [value])
  132. return
  133. prior = super(_OMD, self).__getitem__(key)
  134. prior[-1] = value
  135. def get(self, key, default=None):
  136. return super(_OMD, self).get(key, [default])[-1]
  137. def getall(self, key):
  138. return super(_OMD, self).__getitem__(key)
  139. def items(self):
  140. """List of (key, last value for key)."""
  141. return [(k, self[k]) for k in self]
  142. def items_all(self):
  143. """List of (key, list of values for key)."""
  144. return [(k, self.getall(k)) for k in self]
  145. class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, object)):
  146. """Implements specifics required to read git style configuration files.
  147. This variation behaves much like the git.config command such that the configuration
  148. will be read on demand based on the filepath given during initialization.
  149. The changes will automatically be written once the instance goes out of scope, but
  150. can be triggered manually as well.
  151. The configuration file will be locked if you intend to change values preventing other
  152. instances to write concurrently.
  153. :note:
  154. The config is case-sensitive even when queried, hence section and option names
  155. must match perfectly.
  156. If used as a context manager, will release the locked file."""
  157. #{ Configuration
  158. # The lock type determines the type of lock to use in new configuration readers.
  159. # They must be compatible to the LockFile interface.
  160. # A suitable alternative would be the BlockingLockFile
  161. t_lock = LockFile
  162. re_comment = re.compile(r'^\s*[#;]')
  163. #} END configuration
  164. optvalueonly_source = r'\s*(?P<option>[^:=\s][^:=]*)'
  165. OPTVALUEONLY = re.compile(optvalueonly_source)
  166. OPTCRE = re.compile(optvalueonly_source + r'\s*(?P<vi>[:=])\s*' + r'(?P<value>.*)$')
  167. del optvalueonly_source
  168. # list of RawConfigParser methods able to change the instance
  169. _mutating_methods_ = ("add_section", "remove_section", "remove_option", "set")
  170. def __init__(self, file_or_files, read_only=True, merge_includes=True):
  171. """Initialize a configuration reader to read the given file_or_files and to
  172. possibly allow changes to it by setting read_only False
  173. :param file_or_files:
  174. A single file path or file objects or multiple of these
  175. :param read_only:
  176. If True, the ConfigParser may only read the data , but not change it.
  177. If False, only a single file path or file object may be given. We will write back the changes
  178. when they happen, or when the ConfigParser is released. This will not happen if other
  179. configuration files have been included
  180. :param merge_includes: if True, we will read files mentioned in [include] sections and merge their
  181. contents into ours. This makes it impossible to write back an individual configuration file.
  182. Thus, if you want to modify a single configuration file, turn this off to leave the original
  183. dataset unaltered when reading it."""
  184. cp.RawConfigParser.__init__(self, dict_type=_OMD)
  185. # Used in python 3, needs to stay in sync with sections for underlying implementation to work
  186. if not hasattr(self, '_proxies'):
  187. self._proxies = self._dict()
  188. self._file_or_files = file_or_files
  189. self._read_only = read_only
  190. self._dirty = False
  191. self._is_initialized = False
  192. self._merge_includes = merge_includes
  193. self._lock = None
  194. self._acquire_lock()
  195. def _acquire_lock(self):
  196. if not self._read_only:
  197. if not self._lock:
  198. if isinstance(self._file_or_files, (tuple, list)):
  199. raise ValueError(
  200. "Write-ConfigParsers can operate on a single file only, multiple files have been passed")
  201. # END single file check
  202. file_or_files = self._file_or_files
  203. if not isinstance(self._file_or_files, string_types):
  204. file_or_files = self._file_or_files.name
  205. # END get filename from handle/stream
  206. # initialize lock base - we want to write
  207. self._lock = self.t_lock(file_or_files)
  208. # END lock check
  209. self._lock._obtain_lock()
  210. # END read-only check
  211. def __del__(self):
  212. """Write pending changes if required and release locks"""
  213. # NOTE: only consistent in PY2
  214. self.release()
  215. def __enter__(self):
  216. self._acquire_lock()
  217. return self
  218. def __exit__(self, exception_type, exception_value, traceback):
  219. self.release()
  220. def release(self):
  221. """Flush changes and release the configuration write lock. This instance must not be used anymore afterwards.
  222. In Python 3, it's required to explicitly release locks and flush changes, as __del__ is not called
  223. deterministically anymore."""
  224. # checking for the lock here makes sure we do not raise during write()
  225. # in case an invalid parser was created who could not get a lock
  226. if self.read_only or (self._lock and not self._lock._has_lock()):
  227. return
  228. try:
  229. try:
  230. self.write()
  231. except IOError:
  232. log.error("Exception during destruction of GitConfigParser", exc_info=True)
  233. except ReferenceError:
  234. # This happens in PY3 ... and usually means that some state cannot be written
  235. # as the sections dict cannot be iterated
  236. # Usually when shutting down the interpreter, don'y know how to fix this
  237. pass
  238. finally:
  239. self._lock._release_lock()
  240. def optionxform(self, optionstr):
  241. """Do not transform options in any way when writing"""
  242. return optionstr
  243. def _read(self, fp, fpname):
  244. """A direct copy of the py2.4 version of the super class's _read method
  245. to assure it uses ordered dicts. Had to change one line to make it work.
  246. Future versions have this fixed, but in fact its quite embarrassing for the
  247. guys not to have done it right in the first place !
  248. Removed big comments to make it more compact.
  249. Made sure it ignores initial whitespace as git uses tabs"""
  250. cursect = None # None, or a dictionary
  251. optname = None
  252. lineno = 0
  253. is_multi_line = False
  254. e = None # None, or an exception
  255. def string_decode(v):
  256. if v[-1] == '\\':
  257. v = v[:-1]
  258. # end cut trailing escapes to prevent decode error
  259. if PY3:
  260. return v.encode(defenc).decode('unicode_escape')
  261. else:
  262. return v.decode('string_escape')
  263. # end
  264. # end
  265. while True:
  266. # we assume to read binary !
  267. line = fp.readline().decode(defenc)
  268. if not line:
  269. break
  270. lineno = lineno + 1
  271. # comment or blank line?
  272. if line.strip() == '' or self.re_comment.match(line):
  273. continue
  274. if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
  275. # no leading whitespace
  276. continue
  277. # is it a section header?
  278. mo = self.SECTCRE.match(line.strip())
  279. if not is_multi_line and mo:
  280. sectname = mo.group('header').strip()
  281. if sectname in self._sections:
  282. cursect = self._sections[sectname]
  283. elif sectname == cp.DEFAULTSECT:
  284. cursect = self._defaults
  285. else:
  286. cursect = self._dict((('__name__', sectname),))
  287. self._sections[sectname] = cursect
  288. self._proxies[sectname] = None
  289. # So sections can't start with a continuation line
  290. optname = None
  291. # no section header in the file?
  292. elif cursect is None:
  293. raise cp.MissingSectionHeaderError(fpname, lineno, line)
  294. # an option line?
  295. elif not is_multi_line:
  296. mo = self.OPTCRE.match(line)
  297. if mo:
  298. # We might just have handled the last line, which could contain a quotation we want to remove
  299. optname, vi, optval = mo.group('option', 'vi', 'value')
  300. if vi in ('=', ':') and ';' in optval and not optval.strip().startswith('"'):
  301. pos = optval.find(';')
  302. if pos != -1 and optval[pos - 1].isspace():
  303. optval = optval[:pos]
  304. optval = optval.strip()
  305. if optval == '""':
  306. optval = ''
  307. # end handle empty string
  308. optname = self.optionxform(optname.rstrip())
  309. if len(optval) > 1 and optval[0] == '"' and optval[-1] != '"':
  310. is_multi_line = True
  311. optval = string_decode(optval[1:])
  312. # end handle multi-line
  313. # preserves multiple values for duplicate optnames
  314. cursect.add(optname, optval)
  315. else:
  316. # check if it's an option with no value - it's just ignored by git
  317. if not self.OPTVALUEONLY.match(line):
  318. if not e:
  319. e = cp.ParsingError(fpname)
  320. e.append(lineno, repr(line))
  321. continue
  322. else:
  323. line = line.rstrip()
  324. if line.endswith('"'):
  325. is_multi_line = False
  326. line = line[:-1]
  327. # end handle quotations
  328. optval = cursect.getlast(optname)
  329. cursect.setlast(optname, optval + string_decode(line))
  330. # END parse section or option
  331. # END while reading
  332. # if any parsing errors occurred, raise an exception
  333. if e:
  334. raise e
  335. def _has_includes(self):
  336. return self._merge_includes and self.has_section('include')
  337. def read(self):
  338. """Reads the data stored in the files we have been initialized with. It will
  339. ignore files that cannot be read, possibly leaving an empty configuration
  340. :return: Nothing
  341. :raise IOError: if a file cannot be handled"""
  342. if self._is_initialized:
  343. return
  344. self._is_initialized = True
  345. if not isinstance(self._file_or_files, (tuple, list)):
  346. files_to_read = [self._file_or_files]
  347. else:
  348. files_to_read = list(self._file_or_files)
  349. # end assure we have a copy of the paths to handle
  350. seen = set(files_to_read)
  351. num_read_include_files = 0
  352. while files_to_read:
  353. file_path = files_to_read.pop(0)
  354. fp = file_path
  355. file_ok = False
  356. if hasattr(fp, "seek"):
  357. self._read(fp, fp.name)
  358. else:
  359. # assume a path if it is not a file-object
  360. try:
  361. with open(file_path, 'rb') as fp:
  362. file_ok = True
  363. self._read(fp, fp.name)
  364. except IOError:
  365. continue
  366. # Read includes and append those that we didn't handle yet
  367. # We expect all paths to be normalized and absolute (and will assure that is the case)
  368. if self._has_includes():
  369. for _, include_path in self.items('include'):
  370. if include_path.startswith('~'):
  371. include_path = osp.expanduser(include_path)
  372. if not osp.isabs(include_path):
  373. if not file_ok:
  374. continue
  375. # end ignore relative paths if we don't know the configuration file path
  376. assert osp.isabs(file_path), "Need absolute paths to be sure our cycle checks will work"
  377. include_path = osp.join(osp.dirname(file_path), include_path)
  378. # end make include path absolute
  379. include_path = osp.normpath(include_path)
  380. if include_path in seen or not os.access(include_path, os.R_OK):
  381. continue
  382. seen.add(include_path)
  383. # insert included file to the top to be considered first
  384. files_to_read.insert(0, include_path)
  385. num_read_include_files += 1
  386. # each include path in configuration file
  387. # end handle includes
  388. # END for each file object to read
  389. # If there was no file included, we can safely write back (potentially) the configuration file
  390. # without altering it's meaning
  391. if num_read_include_files == 0:
  392. self._merge_includes = False
  393. # end
  394. def _write(self, fp):
  395. """Write an .ini-format representation of the configuration state in
  396. git compatible format"""
  397. def write_section(name, section_dict):
  398. fp.write(("[%s]\n" % name).encode(defenc))
  399. for (key, values) in section_dict.items_all():
  400. if key == "__name__":
  401. continue
  402. for v in values:
  403. fp.write(("\t%s = %s\n" % (key, self._value_to_string(v).replace('\n', '\n\t'))).encode(defenc))
  404. # END if key is not __name__
  405. # END section writing
  406. if self._defaults:
  407. write_section(cp.DEFAULTSECT, self._defaults)
  408. for name, value in self._sections.items():
  409. write_section(name, value)
  410. def items(self, section_name):
  411. """:return: list((option, value), ...) pairs of all items in the given section"""
  412. return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']
  413. def items_all(self, section_name):
  414. """:return: list((option, [values...]), ...) pairs of all items in the given section"""
  415. rv = _OMD(self._defaults)
  416. for k, vs in self._sections[section_name].items_all():
  417. if k == '__name__':
  418. continue
  419. if k in rv and rv.getall(k) == vs:
  420. continue
  421. for v in vs:
  422. rv.add(k, v)
  423. return rv.items_all()
  424. @needs_values
  425. def write(self):
  426. """Write changes to our file, if there are changes at all
  427. :raise IOError: if this is a read-only writer instance or if we could not obtain
  428. a file lock"""
  429. self._assure_writable("write")
  430. if not self._dirty:
  431. return
  432. if isinstance(self._file_or_files, (list, tuple)):
  433. raise AssertionError("Cannot write back if there is not exactly a single file to write to, have %i files"
  434. % len(self._file_or_files))
  435. # end assert multiple files
  436. if self._has_includes():
  437. log.debug("Skipping write-back of configuration file as include files were merged in." +
  438. "Set merge_includes=False to prevent this.")
  439. return
  440. # end
  441. fp = self._file_or_files
  442. # we have a physical file on disk, so get a lock
  443. is_file_lock = isinstance(fp, string_types + (FileType, ))
  444. if is_file_lock:
  445. self._lock._obtain_lock()
  446. if not hasattr(fp, "seek"):
  447. with open(self._file_or_files, "wb") as fp:
  448. self._write(fp)
  449. else:
  450. fp.seek(0)
  451. # make sure we do not overwrite into an existing file
  452. if hasattr(fp, 'truncate'):
  453. fp.truncate()
  454. self._write(fp)
  455. def _assure_writable(self, method_name):
  456. if self.read_only:
  457. raise IOError("Cannot execute non-constant method %s.%s" % (self, method_name))
  458. def add_section(self, section):
  459. """Assures added options will stay in order"""
  460. return super(GitConfigParser, self).add_section(section)
  461. @property
  462. def read_only(self):
  463. """:return: True if this instance may change the configuration file"""
  464. return self._read_only
  465. def get_value(self, section, option, default=None):
  466. """Get an option's value.
  467. If multiple values are specified for this option in the section, the
  468. last one specified is returned.
  469. :param default:
  470. If not None, the given default value will be returned in case
  471. the option did not exist
  472. :return: a properly typed value, either int, float or string
  473. :raise TypeError: in case the value could not be understood
  474. Otherwise the exceptions known to the ConfigParser will be raised."""
  475. try:
  476. valuestr = self.get(section, option)
  477. except Exception:
  478. if default is not None:
  479. return default
  480. raise
  481. return self._string_to_value(valuestr)
  482. def get_values(self, section, option, default=None):
  483. """Get an option's values.
  484. If multiple values are specified for this option in the section, all are
  485. returned.
  486. :param default:
  487. If not None, a list containing the given default value will be
  488. returned in case the option did not exist
  489. :return: a list of properly typed values, either int, float or string
  490. :raise TypeError: in case the value could not be understood
  491. Otherwise the exceptions known to the ConfigParser will be raised."""
  492. try:
  493. lst = self._sections[section].getall(option)
  494. except Exception:
  495. if default is not None:
  496. return [default]
  497. raise
  498. return [self._string_to_value(valuestr) for valuestr in lst]
  499. def _string_to_value(self, valuestr):
  500. types = (int, float)
  501. for numtype in types:
  502. try:
  503. val = numtype(valuestr)
  504. # truncated value ?
  505. if val != float(valuestr):
  506. continue
  507. return val
  508. except (ValueError, TypeError):
  509. continue
  510. # END for each numeric type
  511. # try boolean values as git uses them
  512. vl = valuestr.lower()
  513. if vl == 'false':
  514. return False
  515. if vl == 'true':
  516. return True
  517. if not isinstance(valuestr, string_types):
  518. raise TypeError(
  519. "Invalid value type: only int, long, float and str are allowed",
  520. valuestr)
  521. return valuestr
  522. def _value_to_string(self, value):
  523. if isinstance(value, (int, float, bool)):
  524. return str(value)
  525. return force_text(value)
  526. @needs_values
  527. @set_dirty_and_flush_changes
  528. def set_value(self, section, option, value):
  529. """Sets the given option in section to the given value.
  530. It will create the section if required, and will not throw as opposed to the default
  531. ConfigParser 'set' method.
  532. :param section: Name of the section in which the option resides or should reside
  533. :param option: Name of the options whose value to set
  534. :param value: Value to set the option to. It must be a string or convertible
  535. to a string
  536. :return: this instance"""
  537. if not self.has_section(section):
  538. self.add_section(section)
  539. self.set(section, option, self._value_to_string(value))
  540. return self
  541. @needs_values
  542. @set_dirty_and_flush_changes
  543. def add_value(self, section, option, value):
  544. """Adds a value for the given option in section.
  545. It will create the section if required, and will not throw as opposed to the default
  546. ConfigParser 'set' method. The value becomes the new value of the option as returned
  547. by 'get_value', and appends to the list of values returned by 'get_values`'.
  548. :param section: Name of the section in which the option resides or should reside
  549. :param option: Name of the option
  550. :param value: Value to add to option. It must be a string or convertible
  551. to a string
  552. :return: this instance"""
  553. if not self.has_section(section):
  554. self.add_section(section)
  555. self._sections[section].add(option, self._value_to_string(value))
  556. return self
  557. def rename_section(self, section, new_name):
  558. """rename the given section to new_name
  559. :raise ValueError: if section doesn't exit
  560. :raise ValueError: if a section with new_name does already exist
  561. :return: this instance
  562. """
  563. if not self.has_section(section):
  564. raise ValueError("Source section '%s' doesn't exist" % section)
  565. if self.has_section(new_name):
  566. raise ValueError("Destination section '%s' already exists" % new_name)
  567. super(GitConfigParser, self).add_section(new_name)
  568. new_section = self._sections[new_name]
  569. for k, vs in self.items_all(section):
  570. new_section.setall(k, vs)
  571. # end for each value to copy
  572. # This call writes back the changes, which is why we don't have the respective decorator
  573. self.remove_section(section)
  574. return self