startup: open selected repository when "Enter" is pressed
[git-cola.git] / cola / gitcfg.py
blobaf12a7072ef11258dc3d868d188fb5f4ac33d27c
1 from __future__ import absolute_import, division, print_function, 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 . import version
14 from .compat import int_types
15 from .git import STDOUT
16 from .compat import ustr
18 BUILTIN_READER = os.environ.get('GIT_COLA_BUILTIN_CONFIG_READER', False)
20 _USER_CONFIG = core.expanduser(join('~', '.gitconfig'))
21 _USER_XDG_CONFIG = core.expanduser(
22 join(core.getenv('XDG_CONFIG_HOME', join('~', '.config')), 'git', 'config')
26 def create(context):
27 """Create GitConfig instances"""
28 return GitConfig(context)
31 def _stat_info(git):
32 # Try /etc/gitconfig as a fallback for the system config
33 paths = [
34 ('system', '/etc/gitconfig'),
35 ('user', _USER_XDG_CONFIG),
36 ('user', _USER_CONFIG),
38 config = git.git_path('config')
39 if config:
40 paths.append(('repo', config))
42 statinfo = []
43 for category, path in paths:
44 try:
45 statinfo.append((category, path, core.stat(path).st_mtime))
46 except OSError:
47 continue
48 return statinfo
51 def _cache_key(git):
52 # Try /etc/gitconfig as a fallback for the system config
53 paths = [
54 '/etc/gitconfig',
55 _USER_XDG_CONFIG,
56 _USER_CONFIG,
58 config = git.git_path('config')
59 if config:
60 paths.append(config)
62 mtimes = []
63 for path in paths:
64 try:
65 mtimes.append(core.stat(path).st_mtime)
66 except OSError:
67 continue
68 return mtimes
71 def _config_to_python(v):
72 """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) # pylint: disable=redefined-variable-type
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._binary_cache = {}
128 self._find_config_files()
130 def reset(self):
131 self._cache_key = None
132 self._configs = []
133 self._config_files.clear()
134 self._attr_cache = {}
135 self._binary_cache = {}
136 self._find_config_files()
137 self.reset_values()
139 def reset_values(self):
140 self._map.clear()
141 self._system.clear()
142 self._user.clear()
143 self._user_or_system.clear()
144 self._repo.clear()
145 self._all.clear()
147 def user(self):
148 return copy.deepcopy(self._user)
150 def repo(self):
151 return copy.deepcopy(self._repo)
153 def all(self):
154 return copy.deepcopy(self._all)
156 def _find_config_files(self):
158 Classify git config files into 'system', 'user', and 'repo'.
160 Populates self._configs with a list of the files in
161 reverse-precedence order. self._config_files is populated with
162 {category: path} where category is one of 'system', 'user', or 'repo'.
165 # Try the git config in git's installation prefix
166 statinfo = _stat_info(self.git)
167 self._configs = [x[1] for x in statinfo]
168 self._config_files = {}
169 for (cat, path, _) in statinfo:
170 self._config_files[cat] = path
172 def _cached(self):
174 Return True when the cache matches.
176 Updates the cache and returns False when the cache does not match.
179 cache_key = _cache_key(self.git)
180 if self._cache_key is None or cache_key != self._cache_key:
181 self._cache_key = cache_key
182 return False
183 return True
185 def update(self):
186 """Read git config value into the system, user and repo dicts."""
187 if self._cached():
188 return
190 self.reset_values()
192 if 'system' in self._config_files:
193 self._system.update(self.read_config(self._config_files['system']))
195 if 'user' in self._config_files:
196 self._user.update(self.read_config(self._config_files['user']))
198 if 'repo' in self._config_files:
199 self._repo.update(self.read_config(self._config_files['repo']))
201 for dct in (self._system, self._user):
202 self._user_or_system.update(dct)
204 for dct in (self._system, self._user, self._repo):
205 self._all.update(dct)
207 self.notify_observers(self.message_updated)
209 def read_config(self, path):
210 """Return git config data from a path as a dictionary."""
212 if BUILTIN_READER:
213 return self._read_config_file(path)
215 dest = {}
216 if version.check_git(self, 'config-includes'):
217 args = ('--null', '--file', path, '--list', '--includes')
218 else:
219 args = ('--null', '--file', path, '--list')
220 config_lines = self.git.config(*args)[STDOUT].split('\0')
221 for line in config_lines:
222 if not line:
223 # the user has an invalid entry in their git config
224 continue
225 k, v = _config_key_value(line, '\n')
226 self._map[k.lower()] = k
227 dest[k] = v
228 return dest
230 def _read_config_file(self, path):
231 """Read a .gitconfig file into a dict"""
233 config = {}
234 header_simple = re.compile(r'^\[(\s+)]$')
235 header_subkey = re.compile(r'^\[(\s+) "(\s+)"\]$')
237 with core.xopen(path, 'rt') as f:
238 file_lines = f.readlines()
240 stripped_lines = [line.strip() for line in file_lines]
241 lines = [line for line in stripped_lines if bool(line)]
242 prefix = ''
243 for line in lines:
244 if line.startswith('#'):
245 continue
247 match = header_simple.match(line)
248 if match:
249 prefix = match.group(1) + '.'
250 continue
251 match = header_subkey.match(line)
252 if match:
253 prefix = match.group(1) + '.' + match.group(2) + '.'
254 continue
256 k, v = _config_key_value(line, '=')
257 k = prefix + k
258 self._map[k.lower()] = k
259 config[k] = v
261 return config
263 def _get(self, src, key, default, fn=None, cached=True):
264 if not cached or not src:
265 self.update()
266 try:
267 value = self._get_with_fallback(src, key)
268 except KeyError:
269 if fn:
270 value = fn()
271 else:
272 value = default
273 return value
275 def _get_with_fallback(self, src, key):
276 try:
277 return src[key]
278 except KeyError:
279 pass
280 key = self._map.get(key.lower(), key)
281 try:
282 return src[key]
283 except KeyError:
284 pass
285 # Allow the final KeyError to bubble up
286 return src[key.lower()]
288 def get(self, key, default=None, fn=None, cached=True):
289 """Return the string value for a config key."""
290 return self._get(self._all, key, default, fn=fn, cached=cached)
292 def get_all(self, key):
293 """Return all values for a key sorted in priority order
295 The purpose of this function is to group the values returned by
296 `git config --show-origin --get-all` so that the relative order is
297 preserved but can still be overridden at each level.
299 One use case is the `cola.icontheme` variable, which is an ordered
300 list of icon themes to load. This value can be set both in
301 ~/.gitconfig as well as .git/config, and we want to allow a
302 relative order to be defined in either file.
304 The problem is that git will read the system /etc/gitconfig,
305 global ~/.gitconfig, and then the local .git/config settings
306 and return them in that order, so we must post-process them to
307 get them in an order which makes sense for use for our values.
308 Otherwise, we cannot replace the order, or make a specific theme used
309 first, in our local .git/config since the native order returned by
310 git will always list the global config before the local one.
312 get_all() allows for this use case by gathering all of the per-config
313 values separately and then orders them according to the expected
314 local > global > system order.
317 result = []
318 status, out, _ = self.git.config(key, z=True, get_all=True, show_origin=True)
319 if status == 0:
320 current_source = ''
321 current_result = []
322 partial_results = []
323 items = [x for x in out.rstrip(chr(0)).split(chr(0)) if x]
324 for i in range(len(items) // 2):
325 source = items[i * 2]
326 value = items[i * 2 + 1]
327 if source != current_source:
328 current_source = source
329 current_result = []
330 partial_results.append(current_result)
331 current_result.append(value)
332 # Git's results are ordered System, Global, Local.
333 # Reverse the order here so that Local has the highest priority.
334 for partial_result in reversed(partial_results):
335 result.extend(partial_result)
337 return result
339 def get_user(self, key, default=None):
340 return self._get(self._user, key, default)
342 def get_repo(self, key, default=None):
343 return self._get(self._repo, key, default)
345 def get_user_or_system(self, key, default=None):
346 return self._get(self._user_or_system, key, default)
348 def set_user(self, key, value):
349 if value in (None, ''):
350 self.git.config('--global', key, unset=True)
351 else:
352 self.git.config('--global', key, python_to_git(value))
353 self.update()
354 msg = self.message_user_config_changed
355 self.notify_observers(msg, key, value)
357 def set_repo(self, key, value):
358 if value in (None, ''):
359 self.git.config(key, unset=True)
360 else:
361 self.git.config(key, python_to_git(value))
362 self.update()
363 msg = self.message_repo_config_changed
364 self.notify_observers(msg, key, value)
366 def find(self, pat):
367 pat = pat.lower()
368 match = fnmatch.fnmatch
369 result = {}
370 if not self._all:
371 self.update()
372 for key, val in self._all.items():
373 if match(key.lower(), pat):
374 result[key] = val
375 return result
377 def is_annex(self):
378 """Return True when git-annex is enabled"""
379 return bool(self.get('annex.uuid', default=False))
381 def gui_encoding(self):
382 return self.get('gui.encoding', default=None)
384 def is_per_file_attrs_enabled(self):
385 return self.get(
386 'cola.fileattributes', fn=lambda: os.path.exists('.gitattributes')
389 def is_binary(self, path):
390 """Return True if the file has the binary attribute set"""
391 if not self.is_per_file_attrs_enabled():
392 return None
393 cache = self._binary_cache
394 try:
395 value = cache[path]
396 except KeyError:
397 value = cache[path] = self._is_binary(path)
398 return value
400 def _is_binary(self, path):
401 """Return the file encoding for a path"""
402 value = self.check_attr('binary', path)
403 return value == 'set'
405 def file_encoding(self, path):
406 if not self.is_per_file_attrs_enabled():
407 return self.gui_encoding()
408 cache = self._attr_cache
409 try:
410 value = cache[path]
411 except KeyError:
412 value = cache[path] = self._file_encoding(path) or self.gui_encoding()
413 return value
415 def _file_encoding(self, path):
416 """Return the file encoding for a path"""
417 encoding = self.check_attr('encoding', path)
418 if encoding in ('unspecified', 'unset', 'set'):
419 result = None
420 else:
421 result = encoding
422 return result
424 def check_attr(self, attr, path):
425 """Check file attributes for a path"""
426 value = None
427 status, out, _ = self.git.check_attr(attr, '--', path)
428 if status == 0:
429 header = '%s: %s: ' % (path, attr)
430 if out.startswith(header):
431 value = out[len(header) :].strip()
432 return value
434 def get_guitool_opts(self, name):
435 """Return the guitool.<name> namespace as a dict
437 The dict keys are simplified so that "guitool.$name.cmd" is accessible
438 as `opts[cmd]`.
441 prefix = len('guitool.%s.' % name)
442 guitools = self.find('guitool.%s.*' % name)
443 return dict([(key[prefix:], value) for (key, value) in guitools.items()])
445 def get_guitool_names(self):
446 guitools = self.find('guitool.*.cmd')
447 prefix = len('guitool.')
448 suffix = len('.cmd')
449 return sorted([name[prefix:-suffix] for (name, _) in guitools.items()])
451 def get_guitool_names_and_shortcuts(self):
452 """Return guitool names and their configured shortcut"""
453 names = self.get_guitool_names()
454 return [(name, self.get('guitool.%s.shortcut' % name)) for name in names]
456 def terminal(self):
457 term = self.get('cola.terminal', default=None)
458 if not term:
459 # find a suitable default terminal
460 term = 'xterm -e' # for mac osx
461 if utils.is_win32():
462 # Try to find Git's sh.exe directory in
463 # one of the typical locations
464 pf = os.environ.get('ProgramFiles', 'C:\\Program Files')
465 pf32 = os.environ.get('ProgramFiles(x86)', 'C:\\Program Files (x86)')
466 pf64 = os.environ.get('ProgramW6432', 'C:\\Program Files')
468 for p in [pf64, pf32, pf, 'C:\\']:
469 candidate = os.path.join(p, 'Git\\bin\\sh.exe')
470 if os.path.isfile(candidate):
471 return candidate
472 return None
473 else:
474 candidates = ('xfce4-terminal', 'konsole', 'gnome-terminal')
475 for basename in candidates:
476 if core.exists('/usr/bin/%s' % basename):
477 if basename == 'gnome-terminal':
478 term = '%s --' % basename
479 else:
480 term = '%s -e' % basename
481 break
482 return term
484 def color(self, key, default):
485 value = self.get('cola.color.%s' % key, default=default)
486 struct_layout = core.encode('BBB')
487 try:
488 # pylint: disable=no-member
489 r, g, b = struct.unpack(struct_layout, unhex(value))
490 except (struct.error, TypeError):
491 # pylint: disable=no-member
492 r, g, b = struct.unpack(struct_layout, unhex(default))
493 return (r, g, b)
495 def hooks(self):
496 """Return the path to the git hooks directory"""
497 gitdir_hooks = self.git.git_path('hooks')
498 return self.get('core.hookspath', default=gitdir_hooks)
500 def hooks_path(self, *paths):
501 """Return a path from within the git hooks directory"""
502 return os.path.join(self.hooks(), *paths)
505 def python_to_git(value):
506 if isinstance(value, bool):
507 return 'true' if value else 'false'
508 if isinstance(value, int_types):
509 return ustr(value)
510 return value