1 from __future__
import division
, absolute_import
, unicode_literals
8 from binascii
import unhexlify
9 from os
.path
import join
13 from cola
import observable
14 from cola
.decorators
import memoize
15 from cola
.git
import STDOUT
16 from cola
.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')),
27 """Return the GitConfig singleton."""
32 # Try /etc/gitconfig as a fallback for the system config
33 paths
= (('system', '/etc/gitconfig'),
34 ('user', _USER_XDG_CONFIG
),
35 ('user', _USER_CONFIG
),
36 ('repo', git
.current().git_path('config')))
38 for category
, path
in paths
:
40 statinfo
.append((category
, path
, core
.stat(path
).st_mtime
))
47 # Try /etc/gitconfig as a fallback for the system config
48 paths
= ('/etc/gitconfig',
51 git
.current().git_path('config'))
55 mtimes
.append(core
.stat(path
).st_mtime
)
61 def _config_to_python(v
):
62 """Convert a Git config string into a Python value"""
64 if v
in ('true', 'yes'):
66 elif v
in ('false', 'no'):
76 def _config_key_value(line
, splitchar
):
77 """Split a config line into a (key, value) pair"""
80 k
, v
= line
.split(splitchar
, 1)
82 # the user has a emptyentry in their git config,
83 # which Git interprets as meaning "true"
86 return k
, _config_to_python(v
)
89 class GitConfig(observable
.Observable
):
90 """Encapsulate access to git-config values."""
92 message_user_config_changed
= 'user_config_changed'
93 message_repo_config_changed
= 'repo_config_changed'
96 observable
.Observable
.__init
__(self
)
97 self
.git
= git
.current()
101 self
._user
_or
_system
= {}
104 self
._cache
_key
= None
106 self
._config
_files
= {}
107 self
._value
_cache
= {}
108 self
._attr
_cache
= {}
109 self
._find
_config
_files
()
115 self
._user
_or
_system
.clear()
118 self
._cache
_key
= None
120 self
._config
_files
.clear()
121 self
._value
_cache
= {}
122 self
._attr
_cache
= {}
123 self
._find
_config
_files
()
126 return copy
.deepcopy(self
._user
)
129 return copy
.deepcopy(self
._repo
)
132 return copy
.deepcopy(self
._all
)
134 def _find_config_files(self
):
136 Classify git config files into 'system', 'user', and 'repo'.
138 Populates self._configs with a list of the files in
139 reverse-precedence order. self._config_files is populated with
140 {category: path} where category is one of 'system', 'user', or 'repo'.
143 # Try the git config in git's installation prefix
144 statinfo
= _stat_info()
145 self
._configs
= map(lambda x
: x
[1], statinfo
)
146 self
._config
_files
= {}
147 for (cat
, path
, mtime
) in statinfo
:
148 self
._config
_files
[cat
] = path
151 """Read config values from git."""
158 Return True when the cache matches.
160 Updates the cache and returns False when the cache does not match.
163 cache_key
= _cache_key()
164 if self
._cache
_key
is None or cache_key
!= self
._cache
_key
:
165 self
._cache
_key
= cache_key
169 def _read_configs(self
):
170 """Read git config value into the system, user and repo dicts."""
174 self
._user
_or
_system
.clear()
178 if 'system' in self
._config
_files
:
180 self
.read_config(self
._config
_files
['system']))
182 if 'user' in self
._config
_files
:
184 self
.read_config(self
._config
_files
['user']))
186 if 'repo' in self
._config
_files
:
188 self
.read_config(self
._config
_files
['repo']))
190 for dct
in (self
._system
, self
._user
):
191 self
._user
_or
_system
.update(dct
)
193 for dct
in (self
._system
, self
._user
, self
._repo
):
194 self
._all
.update(dct
)
196 def read_config(self
, path
):
197 """Return git config data from a path as a dictionary."""
200 return self
._read
_config
_file
(path
)
203 args
= ('--null', '--file', path
, '--list')
204 config_lines
= self
.git
.config(*args
)[STDOUT
].split('\0')
205 for line
in config_lines
:
207 # the user has an invalid entry in their git config
209 k
, v
= _config_key_value(line
, '\n')
210 self
._map
[k
.lower()] = k
214 def _read_config_file(self
, path
):
215 """Read a .gitconfig file into a dict"""
218 header_simple
= re
.compile(r
'^\[(\s+)]$')
219 header_subkey
= re
.compile(r
'^\[(\s+) "(\s+)"\]$')
221 with core
.xopen(path
, 'rt') as f
:
222 lines
= filter(bool, [line
.strip() for line
in f
.readlines()])
226 if line
.startswith('#'):
229 match
= header_simple
.match(line
)
231 prefix
= match
.group(1) + '.'
233 match
= header_subkey
.match(line
)
235 prefix
= match
.group(1) + '.' + match
.group(2) + '.'
238 k
, v
= _config_key_value(line
, '=')
240 self
._map
[k
.lower()] = k
245 def _get(self
, src
, key
, default
):
248 value
= self
._get
_with
_fallback
(src
, key
)
253 def _get_with_fallback(self
, src
, key
):
258 key
= self
._map
.get(key
.lower(), key
)
263 # Allow the final KeyError to bubble up
264 return src
[key
.lower()]
266 def get(self
, key
, default
=None):
267 """Return the string value for a config key."""
268 return self
._get
(self
._all
, key
, default
)
270 def get_user(self
, key
, default
=None):
271 return self
._get
(self
._user
, key
, default
)
273 def get_repo(self
, key
, default
=None):
274 return self
._get
(self
._repo
, key
, default
)
276 def get_user_or_system(self
, key
, default
=None):
277 return self
._get
(self
._user
_or
_system
, key
, default
)
279 def python_to_git(self
, value
):
280 if type(value
) is bool:
285 if type(value
) is int:
289 def set_user(self
, key
, value
):
293 self
.git
.config('--global', key
, self
.python_to_git(value
))
295 msg
= self
.message_user_config_changed
296 self
.notify_observers(msg
, key
, value
)
298 def set_repo(self
, key
, value
):
299 self
.git
.config(key
, self
.python_to_git(value
))
301 msg
= self
.message_repo_config_changed
302 self
.notify_observers(msg
, key
, value
)
304 def unset_user(self
, key
):
305 self
.git
.config('--global', '--unset', key
)
307 msg
= self
.message_repo_config_changed
308 self
.notify_observers(msg
, key
, None)
312 match
= fnmatch
.fnmatch
315 for key
, val
in self
._all
.items():
316 if match(key
.lower(), pat
):
320 def get_cached(self
, key
, default
=None):
321 cache
= self
._value
_cache
325 value
= cache
[key
] = self
.get(key
, default
=default
)
328 def gui_encoding(self
):
329 return self
.get_cached('gui.encoding', default
='utf-8')
331 def is_per_file_attrs_enabled(self
):
332 return self
.get_cached('cola.fileattributes', default
=False)
334 def file_encoding(self
, path
):
335 if not self
.is_per_file_attrs_enabled():
336 return self
.gui_encoding()
337 cache
= self
._attr
_cache
341 value
= cache
[path
] = (self
._file
_encoding
(path
) or
345 def _file_encoding(self
, path
):
346 """Return the file encoding for a path"""
347 status
, out
, err
= self
.git
.check_attr('encoding', '--', path
)
350 header
= '%s: encoding: ' % path
351 if out
.startswith(header
):
352 encoding
= out
[len(header
):].strip()
353 if (encoding
!= 'unspecified' and
354 encoding
!= 'unset' and
359 def get_guitool_opts(self
, name
):
360 """Return the guitool.<name> namespace as a dict
362 The dict keys are simplified so that "guitool.$name.cmd" is accessible
366 prefix
= len('guitool.%s.' % name
)
367 guitools
= self
.find('guitool.%s.*' % name
)
368 return dict([(key
[prefix
:], value
)
369 for (key
, value
) in guitools
.items()])
371 def get_guitool_names(self
):
372 guitools
= self
.find('guitool.*.cmd')
373 prefix
= len('guitool.')
375 return sorted([name
[prefix
:-suffix
]
376 for (name
, cmd
) in guitools
.items()])
378 def get_guitool_names_and_shortcuts(self
):
379 """Return guitool names and their configured shortcut"""
380 names
= self
.get_guitool_names()
381 return [(name
, self
.get('guitool.%s.shortcut' % name
)) for name
in names
]
384 term
= self
.get('cola.terminal', None)
386 # find a suitable default terminal
387 term
= 'xterm -e' # for mac osx
388 candidates
= ('xfce4-terminal', 'konsole')
389 for basename
in candidates
:
390 if core
.exists('/usr/bin/%s' % basename
):
391 term
= '%s -e' % basename
395 def color(self
, key
, default
):
396 string
= self
.get('cola.color.%s' % key
, default
)
397 string
= core
.encode(string
)
398 default
= core
.encode(default
)
399 struct_layout
= core
.encode('BBB')
401 r
, g
, b
= struct
.unpack(struct_layout
, unhexlify(string
))
403 r
, g
, b
= struct
.unpack(struct_layout
, unhexlify(default
))