1
# Copyright (C) 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Rule-based definition of preferences for selected files in selected branches.
19
See ``bzr help rules`` for details.
27
from bzrlib.util.configobj import configobj
30
# Name of the file holding rules in a tree
31
RULES_TREE_FILENAME = ".bzrrules"
34
class _RulesSearcher(object):
35
"""An object that provides rule-based preferences."""
37
def get_items(self, path, names=None):
38
"""Return the preferences for a path as a sequence of name,value tuples.
40
:param path: tree relative path
41
:param names: the list of preferences to lookup - None for all
42
:return: None if no rule matched, otherwise a sequence of name,value
43
tuples. If names is not None, the sequence is the same length as
44
names, tuple order matches the order in names, and undefined
45
preferences are given the value None.
47
raise NotImplementedError(self.get_items)
50
class _IniBasedRulesSearcher(_RulesSearcher):
52
def __init__(self, inifile):
53
"""Construct a _RulesSearcher based on an ini file.
55
The content will be decoded as utf-8.
57
:param inifile: the name of the file or a sequence of lines.
59
options = {'encoding': 'utf-8'}
60
self._cfg = configobj.ConfigObj(inifile, options=options)
61
patterns = self._cfg.keys()
63
self._globster = globbing._OrderedGlobster(patterns)
67
def get_items(self, path, names=None):
68
"""See _RulesSearcher.get_items."""
69
if self._globster is None:
71
pat = self._globster.match(path)
77
return tuple(all.items())
79
return tuple((k, all.get(k)) for k in names)
82
class _StackedRulesSearcher(_RulesSearcher):
84
def __init__(self, searchers):
85
"""Construct a _RulesSearcher based on a stack of other ones.
87
:param searchers: a sequence of searchers.
89
self.searchers = searchers
91
def get_items(self, path, names=None):
92
"""See _RulesSearcher.get_items."""
93
for searcher in self.searchers:
94
result = searcher.get_items(path, names)
95
if result is not None:
100
def rules_filename():
101
"""Return the default rules filename."""
102
return osutils.pathjoin(config.config_dir(), 'rules')
105
# The object providing default rules
106
_per_user_searcher = _IniBasedRulesSearcher(rules_filename())