CHANGES: add a link to issue 890
[git-cola.git] / cola / gitcfg.py
blobe3c0ad2bafe8e1182087e9394e44542c0dedecd0
1 from __future__ import division, absolute_import, unicode_literals
2 from binascii import unhexlify
3 import copy
4 import fnmatch
5 import os
6 from os.path import join
7 import re
8 import struct
10 from . import core
11 from . import observable
12 from . import utils
13 from .compat import int_types
14 from .git import STDOUT
15 from .compat import ustr
17 BUILTIN_READER = os.environ.get('GIT_COLA_BUILTIN_CONFIG_READER', False)
19 _USER_CONFIG = core.expanduser(join('~', '.gitconfig'))
20 _USER_XDG_CONFIG = core.expanduser(
21 join(core.getenv('XDG_CONFIG_HOME', join('~', '.config')), 'git', 'config')
25 def create(context):
26 """Create GitConfig instances"""
27 return GitConfig(context)
30 def _stat_info(git):
31 # Try /etc/gitconfig as a fallback for the system config
32 paths = [
33 ('system', '/etc/gitconfig'),
34 ('user', _USER_XDG_CONFIG),
35 ('user', _USER_CONFIG),
37 config = git.git_path('config')
38 if config:
39 paths.append(('repo', config))
41 statinfo = []
42 for category, path in paths:
43 try:
44 statinfo.append((category, path, core.stat(path).st_mtime))
45 except OSError:
46 continue
47 return statinfo
50 def _cache_key(git):
51 # Try /etc/gitconfig as a fallback for the system config
52 paths = [
53 '/etc/gitconfig',
54 _USER_XDG_CONFIG,
55 _USER_CONFIG,
57 config = git.git_path('config')
58 if config:
59 paths.append(config)
61 mtimes = []
62 for path in paths:
63 try:
64 mtimes.append(core.stat(path).st_mtime)
65 except OSError:
66 continue
67 return mtimes
70 def _config_to_python(v):
71 """Convert a Git config string into a Python value"""
73 if v in ('true', 'yes'):
74 v = True
75 elif v in ('false', 'no'):
76 v = False
77 else:
78 try:
79 v = int(v)
80 except ValueError:
81 pass
82 return v
85 def unhex(value):
86 """Convert a value (int or hex string) into bytes"""
87 if isinstance(value, int_types):
88 # If the value is an integer then it's a value that was converted
89 # by the config reader. Zero-pad it into a 6-digit hex number.
90 value = '%06d' % value
91 return unhexlify(core.encode(value.lstrip('#')))
94 def _config_key_value(line, splitchar):
95 """Split a config line into a (key, value) pair"""
97 try:
98 k, v = line.split(splitchar, 1)
99 except ValueError:
100 # the user has an empty entry in their git config,
101 # which Git interprets as meaning "true"
102 k = line
103 v = 'true'
104 return k, _config_to_python(v)
107 class GitConfig(observable.Observable):
108 """Encapsulate access to git-config values."""
110 message_user_config_changed = 'user_config_changed'
111 message_repo_config_changed = 'repo_config_changed'
112 message_updated = 'updated'
114 def __init__(self, context):
115 observable.Observable.__init__(self)
116 self.git = context.git
117 self._map = {}
118 self._system = {}
119 self._user = {}
120 self._user_or_system = {}
121 self._repo = {}
122 self._all = {}
123 self._cache_key = None
124 self._configs = []
125 self._config_files = {}
126 self._attr_cache = {}
127 self._find_config_files()
129 def reset(self):
130 self._cache_key = None
131 self._configs = []
132 self._config_files.clear()
133 self._attr_cache = {}
134 self._find_config_files()
135 self.reset_values()
137 def reset_values(self):
138 self._map.clear()
139 self._system.clear()
140 self._user.clear()
141 self._user_or_system.clear()
142 self._repo.clear()
143 self._all.clear()
145 def user(self):
146 return copy.deepcopy(self._user)
148 def repo(self):
149 return copy.deepcopy(self._repo)
151 def all(self):
152 return copy.deepcopy(self._all)
154 def _find_config_files(self):
156 Classify git config files into 'system', 'user', and 'repo'.
158 Populates self._configs with a list of the files in
159 reverse-precedence order. self._config_files is populated with
160 {category: path} where category is one of 'system', 'user', or 'repo'.
163 # Try the git config in git's installation prefix
164 statinfo = _stat_info(self.git)
165 self._configs = [x[1] for x in statinfo]
166 self._config_files = {}
167 for (cat, path, _) in statinfo:
168 self._config_files[cat] = path
170 def _cached(self):
172 Return True when the cache matches.
174 Updates the cache and returns False when the cache does not match.
177 cache_key = _cache_key(self.git)
178 if self._cache_key is None or cache_key != self._cache_key:
179 self._cache_key = cache_key
180 return False
181 return True
183 def update(self):
184 """Read git config value into the system, user and repo dicts."""
185 if self._cached():
186 return
188 self.reset_values()
190 if 'system' in self._config_files:
191 self._system.update(self.read_config(self._config_files['system']))
193 if 'user' in self._config_files:
194 self._user.update(self.read_config(self._config_files['user']))
196 if 'repo' in self._config_files:
197 self._repo.update(self.read_config(self._config_files['repo']))
199 for dct in (self._system, self._user):
200 self._user_or_system.update(dct)
202 for dct in (self._system, self._user, self._repo):
203 self._all.update(dct)
205 self.notify_observers(self.message_updated)
207 def read_config(self, path):
208 """Return git config data from a path as a dictionary."""
210 if BUILTIN_READER:
211 return self._read_config_file(path)
213 dest = {}
214 args = ('--null', '--file', path, '--list')
215 config_lines = self.git.config(*args)[STDOUT].split('\0')
216 for line in config_lines:
217 if not line:
218 # the user has an invalid entry in their git config
219 continue
220 k, v = _config_key_value(line, '\n')
221 self._map[k.lower()] = k
222 dest[k] = v
223 return dest
225 def _read_config_file(self, path):
226 """Read a .gitconfig file into a dict"""
228 config = {}
229 header_simple = re.compile(r'^\[(\s+)]$')
230 header_subkey = re.compile(r'^\[(\s+) "(\s+)"\]$')
232 with core.xopen(path, 'rt') as f:
233 file_lines = f.readlines()
235 stripped_lines = [line.strip() for line in file_lines]
236 lines = [line for line in stripped_lines if bool(line)]
237 prefix = ''
238 for line in lines:
239 if line.startswith('#'):
240 continue
242 match = header_simple.match(line)
243 if match:
244 prefix = match.group(1) + '.'
245 continue
246 match = header_subkey.match(line)
247 if match:
248 prefix = match.group(1) + '.' + match.group(2) + '.'
249 continue
251 k, v = _config_key_value(line, '=')
252 k = prefix + k
253 self._map[k.lower()] = k
254 config[k] = v
256 return config
258 def _get(self, src, key, default, fn=None, cached=True):
259 if not cached or not src:
260 self.update()
261 try:
262 value = self._get_with_fallback(src, key)
263 except KeyError:
264 if fn:
265 value = fn()
266 else:
267 value = default
268 return value
270 def _get_with_fallback(self, src, key):
271 try:
272 return src[key]
273 except KeyError:
274 pass
275 key = self._map.get(key.lower(), key)
276 try:
277 return src[key]
278 except KeyError:
279 pass
280 # Allow the final KeyError to bubble up
281 return src[key.lower()]
283 def get(self, key, default=None, fn=None, cached=True):
284 """Return the string value for a config key."""
285 return self._get(self._all, key, default, fn=fn, cached=cached)
287 def get_all(self, key):
288 """Return all values for a key sorted in priority order
290 The purpose of this function is to group the values returned by
291 `git config --show-origin --get-all` so that the relative order is
292 preserved but can still be overridden at each level.
294 One use case is the `cola.icontheme` variable, which is an ordered
295 list of icon themes to load. This value can be set both in
296 ~/.gitconfig as well as .git/config, and we want to allow a
297 relative order to be defined in either file.
299 The problem is that git will read the system /etc/gitconfig,
300 global ~/.gitconfig, and then the local .git/config settings
301 and return them in that order, so we must post-process them to
302 get them in an order which makes sense for use for our values.
303 Otherwise, we cannot replace the order, or make a specific theme used
304 first, in our local .git/config since the native order returned by
305 git will always list the global config before the local one.
307 get_all() allows for this use case by gathering all of the per-config
308 values separately and then orders them according to the expected
309 local > global > system order.
312 result = []
313 status, out, _ = self.git.config(key, z=True, get_all=True, show_origin=True)
314 if status == 0:
315 current_source = ''
316 current_result = []
317 partial_results = []
318 items = [x for x in out.rstrip(chr(0)).split(chr(0)) if x]
319 for i in range(len(items) // 2):
320 source = items[i * 2]
321 value = items[i * 2 + 1]
322 if source != current_source:
323 current_source = source
324 current_result = []
325 partial_results.append(current_result)
326 current_result.append(value)
327 # Git's results are ordered System, Global, Local.
328 # Reverse the order here so that Local has the highest priority.
329 for partial_result in reversed(partial_results):
330 result.extend(partial_result)
332 return result
334 def get_user(self, key, default=None):
335 return self._get(self._user, key, default)
337 def get_repo(self, key, default=None):
338 return self._get(self._repo, key, default)
340 def get_user_or_system(self, key, default=None):
341 return self._get(self._user_or_system, key, default)
343 def set_user(self, key, value):
344 if value in (None, ''):
345 self.git.config('--global', key, unset=True)
346 else:
347 self.git.config('--global', key, python_to_git(value))
348 self.update()
349 msg = self.message_user_config_changed
350 self.notify_observers(msg, key, value)
352 def set_repo(self, key, value):
353 if value in (None, ''):
354 self.git.config(key, unset=True)
355 else:
356 self.git.config(key, python_to_git(value))
357 self.update()
358 msg = self.message_repo_config_changed
359 self.notify_observers(msg, key, value)
361 def find(self, pat):
362 pat = pat.lower()
363 match = fnmatch.fnmatch
364 result = {}
365 if not self._all:
366 self.update()
367 for key, val in self._all.items():
368 if match(key.lower(), pat):
369 result[key] = val
370 return result
372 def is_annex(self):
373 """Return True when git-annex is enabled"""
374 return bool(self.get('annex.uuid', default=False))
376 def gui_encoding(self):
377 return self.get('gui.encoding', default=None)
379 def is_per_file_attrs_enabled(self):
380 return self.get(
381 'cola.fileattributes', fn=lambda: os.path.exists('.gitattributes')
384 def file_encoding(self, path):
385 if not self.is_per_file_attrs_enabled():
386 return self.gui_encoding()
387 cache = self._attr_cache
388 try:
389 value = cache[path]
390 except KeyError:
391 value = cache[path] = self._file_encoding(path) or self.gui_encoding()
392 return value
394 def _file_encoding(self, path):
395 """Return the file encoding for a path"""
396 status, out, _ = self.git.check_attr('encoding', '--', path)
397 if status != 0:
398 return None
399 header = '%s: encoding: ' % path
400 if out.startswith(header):
401 encoding = out[len(header) :].strip()
402 if encoding not in ('unspecified', 'unset', 'set'):
403 return encoding
404 return None
406 def get_guitool_opts(self, name):
407 """Return the guitool.<name> namespace as a dict
409 The dict keys are simplified so that "guitool.$name.cmd" is accessible
410 as `opts[cmd]`.
413 prefix = len('guitool.%s.' % name)
414 guitools = self.find('guitool.%s.*' % name)
415 return dict([(key[prefix:], value) for (key, value) in guitools.items()])
417 def get_guitool_names(self):
418 guitools = self.find('guitool.*.cmd')
419 prefix = len('guitool.')
420 suffix = len('.cmd')
421 return sorted([name[prefix:-suffix] for (name, _) in guitools.items()])
423 def get_guitool_names_and_shortcuts(self):
424 """Return guitool names and their configured shortcut"""
425 names = self.get_guitool_names()
426 return [(name, self.get('guitool.%s.shortcut' % name)) for name in names]
428 def terminal(self):
429 term = self.get('cola.terminal', default=None)
430 if not term:
431 # find a suitable default terminal
432 term = 'xterm -e' # for mac osx
433 if utils.is_win32():
434 # Try to find Git's sh.exe directory in
435 # one of the typical locations
436 pf = os.environ.get('ProgramFiles', 'C:\\Program Files')
437 pf32 = os.environ.get('ProgramFiles(x86)', 'C:\\Program Files (x86)')
438 pf64 = os.environ.get('ProgramW6432', 'C:\\Program Files')
440 for p in [pf64, pf32, pf, 'C:\\']:
441 candidate = os.path.join(p, 'Git\\bin\\sh.exe')
442 if os.path.isfile(candidate):
443 return candidate
444 return None
445 else:
446 candidates = ('xfce4-terminal', 'konsole', 'gnome-terminal')
447 for basename in candidates:
448 if core.exists('/usr/bin/%s' % basename):
449 if basename == 'gnome-terminal':
450 term = '%s --' % basename
451 else:
452 term = '%s -e' % basename
453 break
454 return term
456 def color(self, key, default):
457 value = self.get('cola.color.%s' % key, default=default)
458 struct_layout = core.encode('BBB')
459 try:
460 r, g, b = struct.unpack(struct_layout, unhex(value))
461 except (struct.error, TypeError):
462 r, g, b = struct.unpack(struct_layout, unhex(default))
463 return (r, g, b)
466 def python_to_git(value):
467 if isinstance(value, bool):
468 return 'true' if value else 'false'
469 if isinstance(value, int_types):
470 return ustr(value)
471 return value