config.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. # config.py - Reading and writing Git config files
  2. # Copyright (C) 2011-2013 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Reading and writing Git configuration files.
  21. TODO:
  22. * preserve formatting when updating configuration files
  23. * treat subsection names as case-insensitive for [branch.foo] style
  24. subsections
  25. """
  26. import errno
  27. import os
  28. import sys
  29. from collections import (
  30. Iterable,
  31. OrderedDict,
  32. MutableMapping,
  33. )
  34. from dulwich.file import GitFile
  35. SENTINAL = object()
  36. def lower_key(key):
  37. if isinstance(key, (bytes, str)):
  38. return key.lower()
  39. if isinstance(key, Iterable):
  40. return type(key)(
  41. map(lower_key, key)
  42. )
  43. return key
  44. class CaseInsensitiveDict(OrderedDict):
  45. @classmethod
  46. def make(cls, dict_in=None):
  47. if isinstance(dict_in, cls):
  48. return dict_in
  49. out = cls()
  50. if dict_in is None:
  51. return out
  52. if not isinstance(dict_in, MutableMapping):
  53. raise TypeError
  54. for key, value in dict_in.items():
  55. out[key] = value
  56. return out
  57. def __setitem__(self, key, value, **kwargs):
  58. key = lower_key(key)
  59. super(CaseInsensitiveDict, self).__setitem__(key, value, **kwargs)
  60. def __getitem__(self, item):
  61. key = lower_key(item)
  62. return super(CaseInsensitiveDict, self).__getitem__(key)
  63. def get(self, key, default=SENTINAL):
  64. try:
  65. return self[key]
  66. except KeyError:
  67. pass
  68. if default is SENTINAL:
  69. return type(self)()
  70. return default
  71. def setdefault(self, key, default=SENTINAL):
  72. try:
  73. return self[key]
  74. except KeyError:
  75. self[key] = self.get(key, default)
  76. return self[key]
  77. class Config(object):
  78. """A Git configuration."""
  79. def get(self, section, name):
  80. """Retrieve the contents of a configuration setting.
  81. :param section: Tuple with section name and optional subsection namee
  82. :param subsection: Subsection name
  83. :return: Contents of the setting
  84. :raise KeyError: if the value is not set
  85. """
  86. raise NotImplementedError(self.get)
  87. def get_boolean(self, section, name, default=None):
  88. """Retrieve a configuration setting as boolean.
  89. :param section: Tuple with section name and optional subsection namee
  90. :param name: Name of the setting, including section and possible
  91. subsection.
  92. :return: Contents of the setting
  93. :raise KeyError: if the value is not set
  94. """
  95. try:
  96. value = self.get(section, name)
  97. except KeyError:
  98. return default
  99. if value.lower() == b"true":
  100. return True
  101. elif value.lower() == b"false":
  102. return False
  103. raise ValueError("not a valid boolean string: %r" % value)
  104. def set(self, section, name, value):
  105. """Set a configuration value.
  106. :param section: Tuple with section name and optional subsection namee
  107. :param name: Name of the configuration value, including section
  108. and optional subsection
  109. :param: Value of the setting
  110. """
  111. raise NotImplementedError(self.set)
  112. def iteritems(self, section):
  113. """Iterate over the configuration pairs for a specific section.
  114. :param section: Tuple with section name and optional subsection namee
  115. :return: Iterator over (name, value) pairs
  116. """
  117. raise NotImplementedError(self.iteritems)
  118. def itersections(self):
  119. """Iterate over the sections.
  120. :return: Iterator over section tuples
  121. """
  122. raise NotImplementedError(self.itersections)
  123. def has_section(self, name):
  124. """Check if a specified section exists.
  125. :param name: Name of section to check for
  126. :return: boolean indicating whether the section exists
  127. """
  128. return (name in self.itersections())
  129. class ConfigDict(Config, MutableMapping):
  130. """Git configuration stored in a dictionary."""
  131. def __init__(self, values=None, encoding=None):
  132. """Create a new ConfigDict."""
  133. if encoding is None:
  134. encoding = sys.getdefaultencoding()
  135. self.encoding = encoding
  136. self._values = CaseInsensitiveDict.make(values)
  137. def __repr__(self):
  138. return "%s(%r)" % (self.__class__.__name__, self._values)
  139. def __eq__(self, other):
  140. return (
  141. isinstance(other, self.__class__) and
  142. other._values == self._values)
  143. def __getitem__(self, key):
  144. return self._values.__getitem__(key)
  145. def __setitem__(self, key, value):
  146. return self._values.__setitem__(key, value)
  147. def __delitem__(self, key):
  148. return self._values.__delitem__(key)
  149. def __iter__(self):
  150. return self._values.__iter__()
  151. def __len__(self):
  152. return self._values.__len__()
  153. @classmethod
  154. def _parse_setting(cls, name):
  155. parts = name.split(".")
  156. if len(parts) == 3:
  157. return (parts[0], parts[1], parts[2])
  158. else:
  159. return (parts[0], None, parts[1])
  160. def _check_section_and_name(self, section, name):
  161. if not isinstance(section, tuple):
  162. section = (section, )
  163. section = tuple([
  164. subsection.encode(self.encoding)
  165. if not isinstance(subsection, bytes) else subsection
  166. for subsection in section
  167. ])
  168. if not isinstance(name, bytes):
  169. name = name.encode(self.encoding)
  170. return section, name
  171. def get(self, section, name):
  172. section, name = self._check_section_and_name(section, name)
  173. if len(section) > 1:
  174. try:
  175. return self._values[section][name]
  176. except KeyError:
  177. pass
  178. return self._values[(section[0],)][name]
  179. def set(self, section, name, value):
  180. section, name = self._check_section_and_name(section, name)
  181. if type(value) not in (bool, bytes):
  182. value = value.encode(self.encoding)
  183. self._values.setdefault(section)[name] = value
  184. def iteritems(self, section):
  185. return self._values.get(section).items()
  186. def itersections(self):
  187. return self._values.keys()
  188. def _format_string(value):
  189. if (value.startswith(b" ") or
  190. value.startswith(b"\t") or
  191. value.endswith(b" ") or
  192. b'#' in value or
  193. value.endswith(b"\t")):
  194. return b'"' + _escape_value(value) + b'"'
  195. else:
  196. return _escape_value(value)
  197. _ESCAPE_TABLE = {
  198. ord(b"\\"): ord(b"\\"),
  199. ord(b"\""): ord(b"\""),
  200. ord(b"n"): ord(b"\n"),
  201. ord(b"t"): ord(b"\t"),
  202. ord(b"b"): ord(b"\b"),
  203. }
  204. _COMMENT_CHARS = [ord(b"#"), ord(b";")]
  205. _WHITESPACE_CHARS = [ord(b"\t"), ord(b" ")]
  206. def _parse_string(value):
  207. value = bytearray(value.strip())
  208. ret = bytearray()
  209. whitespace = bytearray()
  210. in_quotes = False
  211. i = 0
  212. while i < len(value):
  213. c = value[i]
  214. if c == ord(b"\\"):
  215. i += 1
  216. try:
  217. v = _ESCAPE_TABLE[value[i]]
  218. except IndexError:
  219. raise ValueError(
  220. "escape character in %r at %d before end of string" %
  221. (value, i))
  222. except KeyError:
  223. raise ValueError(
  224. "escape character followed by unknown character "
  225. "%s at %d in %r" % (value[i], i, value))
  226. if whitespace:
  227. ret.extend(whitespace)
  228. whitespace = bytearray()
  229. ret.append(v)
  230. elif c == ord(b"\""):
  231. in_quotes = (not in_quotes)
  232. elif c in _COMMENT_CHARS and not in_quotes:
  233. # the rest of the line is a comment
  234. break
  235. elif c in _WHITESPACE_CHARS:
  236. whitespace.append(c)
  237. else:
  238. if whitespace:
  239. ret.extend(whitespace)
  240. whitespace = bytearray()
  241. ret.append(c)
  242. i += 1
  243. if in_quotes:
  244. raise ValueError("missing end quote")
  245. return bytes(ret)
  246. def _escape_value(value):
  247. """Escape a value."""
  248. value = value.replace(b"\\", b"\\\\")
  249. value = value.replace(b"\n", b"\\n")
  250. value = value.replace(b"\t", b"\\t")
  251. value = value.replace(b"\"", b"\\\"")
  252. return value
  253. def _check_variable_name(name):
  254. for i in range(len(name)):
  255. c = name[i:i+1]
  256. if not c.isalnum() and c != b'-':
  257. return False
  258. return True
  259. def _check_section_name(name):
  260. for i in range(len(name)):
  261. c = name[i:i+1]
  262. if not c.isalnum() and c not in (b'-', b'.'):
  263. return False
  264. return True
  265. def _strip_comments(line):
  266. comment_bytes = {ord(b"#"), ord(b";")}
  267. quote = ord(b'"')
  268. string_open = False
  269. # Normalize line to bytearray for simple 2/3 compatibility
  270. for i, character in enumerate(bytearray(line)):
  271. # Comment characters outside balanced quotes denote comment start
  272. if character == quote:
  273. string_open = not string_open
  274. elif not string_open and character in comment_bytes:
  275. return line[:i]
  276. return line
  277. class ConfigFile(ConfigDict):
  278. """A Git configuration file, like .git/config or ~/.gitconfig.
  279. """
  280. @classmethod
  281. def from_file(cls, f):
  282. """Read configuration from a file-like object."""
  283. ret = cls()
  284. section = None
  285. setting = None
  286. for lineno, line in enumerate(f.readlines()):
  287. line = line.lstrip()
  288. if setting is None:
  289. # Parse section header ("[bla]")
  290. if len(line) > 0 and line[:1] == b"[":
  291. line = _strip_comments(line).rstrip()
  292. try:
  293. last = line.index(b"]")
  294. except ValueError:
  295. raise ValueError("expected trailing ]")
  296. pts = line[1:last].split(b" ", 1)
  297. line = line[last+1:]
  298. if len(pts) == 2:
  299. if pts[1][:1] != b"\"" or pts[1][-1:] != b"\"":
  300. raise ValueError(
  301. "Invalid subsection %r" % pts[1])
  302. else:
  303. pts[1] = pts[1][1:-1]
  304. if not _check_section_name(pts[0]):
  305. raise ValueError("invalid section name %r" %
  306. pts[0])
  307. section = (pts[0], pts[1])
  308. else:
  309. if not _check_section_name(pts[0]):
  310. raise ValueError(
  311. "invalid section name %r" % pts[0])
  312. pts = pts[0].split(b".", 1)
  313. if len(pts) == 2:
  314. section = (pts[0], pts[1])
  315. else:
  316. section = (pts[0], )
  317. ret._values.setdefault(section)
  318. if _strip_comments(line).strip() == b"":
  319. continue
  320. if section is None:
  321. raise ValueError("setting %r without section" % line)
  322. try:
  323. setting, value = line.split(b"=", 1)
  324. except ValueError:
  325. setting = line
  326. value = b"true"
  327. setting = setting.strip()
  328. if not _check_variable_name(setting):
  329. raise ValueError("invalid variable name %s" % setting)
  330. if value.endswith(b"\\\n"):
  331. continuation = value[:-2]
  332. else:
  333. continuation = None
  334. value = _parse_string(value)
  335. ret._values[section][setting] = value
  336. setting = None
  337. else: # continuation line
  338. if line.endswith(b"\\\n"):
  339. continuation += line[:-2]
  340. else:
  341. continuation += line
  342. value = _parse_string(continuation)
  343. ret._values[section][setting] = value
  344. continuation = None
  345. setting = None
  346. return ret
  347. @classmethod
  348. def from_path(cls, path):
  349. """Read configuration from a file on disk."""
  350. with GitFile(path, 'rb') as f:
  351. ret = cls.from_file(f)
  352. ret.path = path
  353. return ret
  354. def write_to_path(self, path=None):
  355. """Write configuration to a file on disk."""
  356. if path is None:
  357. path = self.path
  358. with GitFile(path, 'wb') as f:
  359. self.write_to_file(f)
  360. def write_to_file(self, f):
  361. """Write configuration to a file-like object."""
  362. for section, values in self._values.items():
  363. try:
  364. section_name, subsection_name = section
  365. except ValueError:
  366. (section_name, ) = section
  367. subsection_name = None
  368. if subsection_name is None:
  369. f.write(b"[" + section_name + b"]\n")
  370. else:
  371. f.write(b"[" + section_name +
  372. b" \"" + subsection_name + b"\"]\n")
  373. for key, value in values.items():
  374. if value is True:
  375. value = b"true"
  376. elif value is False:
  377. value = b"false"
  378. else:
  379. value = _format_string(value)
  380. f.write(b"\t" + key + b" = " + value + b"\n")
  381. class StackedConfig(Config):
  382. """Configuration which reads from multiple config files.."""
  383. def __init__(self, backends, writable=None):
  384. self.backends = backends
  385. self.writable = writable
  386. def __repr__(self):
  387. return "<%s for %r>" % (self.__class__.__name__, self.backends)
  388. @classmethod
  389. def default(cls):
  390. return cls(cls.default_backends())
  391. @classmethod
  392. def default_backends(cls):
  393. """Retrieve the default configuration.
  394. See git-config(1) for details on the files searched.
  395. """
  396. paths = []
  397. paths.append(os.path.expanduser("~/.gitconfig"))
  398. xdg_config_home = os.environ.get(
  399. "XDG_CONFIG_HOME", os.path.expanduser("~/.config/"),
  400. )
  401. paths.append(os.path.join(xdg_config_home, "git", "config"))
  402. if "GIT_CONFIG_NOSYSTEM" not in os.environ:
  403. paths.append("/etc/gitconfig")
  404. backends = []
  405. for path in paths:
  406. try:
  407. cf = ConfigFile.from_path(path)
  408. except (IOError, OSError) as e:
  409. if e.errno != errno.ENOENT:
  410. raise
  411. else:
  412. continue
  413. backends.append(cf)
  414. return backends
  415. def get(self, section, name):
  416. if not isinstance(section, tuple):
  417. section = (section, )
  418. for backend in self.backends:
  419. try:
  420. return backend.get(section, name)
  421. except KeyError:
  422. pass
  423. raise KeyError(name)
  424. def set(self, section, name, value):
  425. if self.writable is None:
  426. raise NotImplementedError(self.set)
  427. return self.writable.set(section, name, value)
  428. def parse_submodules(config):
  429. """Parse a gitmodules GitConfig file, returning submodules.
  430. :param config: A `ConfigFile`
  431. :return: list of tuples (submodule path, url, name),
  432. where name is quoted part of the section's name.
  433. """
  434. for section in config.keys():
  435. section_kind, section_name = section
  436. if section_kind == b'submodule':
  437. sm_path = config.get(section, b'path')
  438. sm_url = config.get(section, b'url')
  439. yield (sm_path, sm_url, section_name)