1 from __future__
import division
, absolute_import
, unicode_literals
2 from binascii
import unhexlify
6 from os
.path
import join
11 from . import observable
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')
27 """Create GitConfig instances"""
28 return GitConfig(context
)
32 # Try /etc/gitconfig as a fallback for the system config
34 ('system', '/etc/gitconfig'),
35 ('user', _USER_XDG_CONFIG
),
36 ('user', _USER_CONFIG
),
38 config
= git
.git_path('config')
40 paths
.append(('repo', config
))
43 for category
, path
in paths
:
45 statinfo
.append((category
, path
, core
.stat(path
).st_mtime
))
52 # Try /etc/gitconfig as a fallback for the system config
58 config
= git
.git_path('config')
65 mtimes
.append(core
.stat(path
).st_mtime
)
71 def _config_to_python(v
):
72 """Convert a Git config string into a Python value"""
74 if v
in ('true', 'yes'):
76 elif v
in ('false', 'no'):
87 """Convert a value (int or hex string) into bytes"""
88 if isinstance(value
, int_types
):
89 # If the value is an integer then it's a value that was converted
90 # by the config reader. Zero-pad it into a 6-digit hex number.
91 value
= '%06d' % value
92 return unhexlify(core
.encode(value
.lstrip('#')))
95 def _config_key_value(line
, splitchar
):
96 """Split a config line into a (key, value) pair"""
99 k
, v
= line
.split(splitchar
, 1)
101 # the user has an empty entry in their git config,
102 # which Git interprets as meaning "true"
105 return k
, _config_to_python(v
)
108 class GitConfig(observable
.Observable
):
109 """Encapsulate access to git-config values."""
111 message_user_config_changed
= 'user_config_changed'
112 message_repo_config_changed
= 'repo_config_changed'
113 message_updated
= 'updated'
115 def __init__(self
, context
):
116 observable
.Observable
.__init
__(self
)
117 self
.git
= context
.git
121 self
._user
_or
_system
= {}
124 self
._cache
_key
= None
126 self
._config
_files
= {}
127 self
._context
= context
128 self
._attr
_cache
= {}
129 self
._find
_config
_files
()
132 self
._cache
_key
= None
134 self
._config
_files
.clear()
135 self
._attr
_cache
= {}
136 self
._find
_config
_files
()
139 def reset_values(self
):
143 self
._user
_or
_system
.clear()
148 return copy
.deepcopy(self
._user
)
151 return copy
.deepcopy(self
._repo
)
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
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
186 """Read git config value into the system, user and repo dicts."""
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."""
213 return self
._read
_config
_file
(path
)
216 if version
.check_git(self
._context
, 'config-includes'):
217 args
= ('--null', '--file', path
, '--list', '--includes')
219 args
= ('--null', '--file', path
, '--list')
220 config_lines
= self
.git
.config(*args
)[STDOUT
].split('\0')
221 for line
in config_lines
:
223 # the user has an invalid entry in their git config
225 k
, v
= _config_key_value(line
, '\n')
226 self
._map
[k
.lower()] = k
230 def _read_config_file(self
, path
):
231 """Read a .gitconfig file into a dict"""
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
)]
244 if line
.startswith('#'):
247 match
= header_simple
.match(line
)
249 prefix
= match
.group(1) + '.'
251 match
= header_subkey
.match(line
)
253 prefix
= match
.group(1) + '.' + match
.group(2) + '.'
256 k
, v
= _config_key_value(line
, '=')
258 self
._map
[k
.lower()] = k
263 def _get(self
, src
, key
, default
, fn
=None, cached
=True):
264 if not cached
or not src
:
267 value
= self
._get
_with
_fallback
(src
, key
)
275 def _get_with_fallback(self
, src
, key
):
280 key
= self
._map
.get(key
.lower(), key
)
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.
318 status
, out
, _
= self
.git
.config(key
, z
=True, get_all
=True, show_origin
=True)
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
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
)
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)
352 self
.git
.config('--global', key
, python_to_git(value
))
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)
361 self
.git
.config(key
, python_to_git(value
))
363 msg
= self
.message_repo_config_changed
364 self
.notify_observers(msg
, key
, value
)
368 match
= fnmatch
.fnmatch
372 for key
, val
in self
._all
.items():
373 if match(key
.lower(), pat
):
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
):
386 'cola.fileattributes', fn
=lambda: os
.path
.exists('.gitattributes')
389 def file_encoding(self
, path
):
390 if not self
.is_per_file_attrs_enabled():
391 return self
.gui_encoding()
392 cache
= self
._attr
_cache
396 value
= cache
[path
] = self
._file
_encoding
(path
) or self
.gui_encoding()
399 def _file_encoding(self
, path
):
400 """Return the file encoding for a path"""
401 status
, out
, _
= self
.git
.check_attr('encoding', '--', path
)
404 header
= '%s: encoding: ' % path
405 if out
.startswith(header
):
406 encoding
= out
[len(header
) :].strip()
407 if encoding
not in ('unspecified', 'unset', 'set'):
411 def get_guitool_opts(self
, name
):
412 """Return the guitool.<name> namespace as a dict
414 The dict keys are simplified so that "guitool.$name.cmd" is accessible
418 prefix
= len('guitool.%s.' % name
)
419 guitools
= self
.find('guitool.%s.*' % name
)
420 return dict([(key
[prefix
:], value
) for (key
, value
) in guitools
.items()])
422 def get_guitool_names(self
):
423 guitools
= self
.find('guitool.*.cmd')
424 prefix
= len('guitool.')
426 return sorted([name
[prefix
:-suffix
] for (name
, _
) in guitools
.items()])
428 def get_guitool_names_and_shortcuts(self
):
429 """Return guitool names and their configured shortcut"""
430 names
= self
.get_guitool_names()
431 return [(name
, self
.get('guitool.%s.shortcut' % name
)) for name
in names
]
434 term
= self
.get('cola.terminal', default
=None)
436 # find a suitable default terminal
437 term
= 'xterm -e' # for mac osx
439 # Try to find Git's sh.exe directory in
440 # one of the typical locations
441 pf
= os
.environ
.get('ProgramFiles', 'C:\\Program Files')
442 pf32
= os
.environ
.get('ProgramFiles(x86)', 'C:\\Program Files (x86)')
443 pf64
= os
.environ
.get('ProgramW6432', 'C:\\Program Files')
445 for p
in [pf64
, pf32
, pf
, 'C:\\']:
446 candidate
= os
.path
.join(p
, 'Git\\bin\\sh.exe')
447 if os
.path
.isfile(candidate
):
451 candidates
= ('xfce4-terminal', 'konsole', 'gnome-terminal')
452 for basename
in candidates
:
453 if core
.exists('/usr/bin/%s' % basename
):
454 if basename
== 'gnome-terminal':
455 term
= '%s --' % basename
457 term
= '%s -e' % basename
461 def color(self
, key
, default
):
462 value
= self
.get('cola.color.%s' % key
, default
=default
)
463 struct_layout
= core
.encode('BBB')
465 r
, g
, b
= struct
.unpack(struct_layout
, unhex(value
))
466 except (struct
.error
, TypeError):
467 r
, g
, b
= struct
.unpack(struct_layout
, unhex(default
))
471 """Return the path to the git hooks directory"""
472 gitdir_hooks
= self
.git
.git_path('hooks')
473 return self
.get('core.hookspath', default
=gitdir_hooks
)
475 def hooks_path(self
, *paths
):
476 """Return a path from within the git hooks directory"""
477 return os
.path
.join(self
.hooks(), *paths
)
480 def python_to_git(value
):
481 if isinstance(value
, bool):
482 return 'true' if value
else 'false'
483 if isinstance(value
, int_types
):