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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
Views are contained within a working tree and normally constructed
20
when first accessed. Clients should do, for example, ...
22
tree.views.lookup_view()
33
_VIEWS_FORMAT_MARKER_RE = re.compile(b'Bazaar views format (\\d+)')
34
_VIEWS_FORMAT1_MARKER = b"Bazaar views format 1\n"
37
class NoSuchView(errors.BzrError):
38
"""A view does not exist.
41
_fmt = u"No such view: %(view_name)s."
43
def __init__(self, view_name):
44
self.view_name = view_name
47
class ViewsNotSupported(errors.BzrError):
48
"""Views are not supported by a tree format.
51
_fmt = ("Views are not supported by %(tree)s;"
52
" use 'brz upgrade' to change your tree to a later format.")
54
def __init__(self, tree):
58
class FileOutsideView(errors.BzrError):
60
_fmt = ('Specified file "%(file_name)s" is outside the current view: '
63
def __init__(self, file_name, view_files):
64
self.file_name = file_name
65
self.view_str = ", ".join(view_files)
69
"""Base class for View managers."""
71
def supports_views(self):
72
raise NotImplementedError(self.supports_views)
75
class PathBasedViews(_Views):
76
"""View storage in an unversioned tree control file.
78
Views are stored in terms of paths relative to the tree root.
80
The top line of the control file is a format marker in the format:
84
where X is an integer number. After this top line, version 1 format is
87
* optional name-values pairs in the format 'name=value'
89
* optional view definitions, one per line in the format
95
where the fields are separated by a nul character (\0). The views file
96
is encoded in utf-8. The only supported keyword in version 1 is
97
'current' which stores the name of the current view, if any.
100
def __init__(self, tree):
106
def supports_views(self):
109
def get_view_info(self):
110
"""Get the current view and dictionary of views.
112
:return: current, views where
113
current = the name of the current view or None if no view is enabled
114
views = a map from view name to list of files/directories
116
self._load_view_info()
117
return self._current, self._views
119
def set_view_info(self, current, views):
120
"""Set the current view and dictionary of views.
122
:param current: the name of the current view or None if no view is
124
:param views: a map from view name to list of files/directories
126
if current is not None and current not in views:
127
raise NoSuchView(current)
128
with self.tree.lock_write():
129
self._current = current
131
self._save_view_info()
133
def lookup_view(self, view_name=None):
134
"""Return the contents of a view.
136
:param view_Name: name of the view or None to lookup the current view
137
:return: the list of files/directories in the requested view
139
self._load_view_info()
141
if view_name is None:
143
view_name = self._current
146
return self._views[view_name]
148
raise NoSuchView(view_name)
150
def set_view(self, view_name, view_files, make_current=True):
151
"""Add or update a view definition.
153
:param view_name: the name of the view
154
:param view_files: the list of files/directories in the view
155
:param make_current: make this view the current one or not
157
with self.tree.lock_write():
158
self._load_view_info()
159
self._views[view_name] = view_files
161
self._current = view_name
162
self._save_view_info()
164
def delete_view(self, view_name):
165
"""Delete a view definition.
167
If the view deleted is the current one, the current view is reset.
169
with self.tree.lock_write():
170
self._load_view_info()
172
del self._views[view_name]
174
raise NoSuchView(view_name)
175
if view_name == self._current:
177
self._save_view_info()
179
def _save_view_info(self):
180
"""Save the current view and all view definitions.
182
Be sure to have initialised self._current and self._views before
185
with self.tree.lock_write():
186
if self._current is None:
189
keywords = {'current': self._current}
190
self.tree._transport.put_bytes(
191
'views', self._serialize_view_content(keywords, self._views))
193
def _load_view_info(self):
194
"""Load the current view and dictionary of view definitions."""
196
with self.tree.lock_read():
198
view_content = self.tree._transport.get_bytes('views')
199
except errors.NoSuchFile:
200
self._current, self._views = None, {}
202
keywords, self._views = \
203
self._deserialize_view_content(view_content)
204
self._current = keywords.get('current')
207
def _serialize_view_content(self, keywords, view_dict):
208
"""Convert view keywords and a view dictionary into a stream."""
209
lines = [_VIEWS_FORMAT1_MARKER]
211
line = "%s=%s\n" % (key, keywords[key])
212
lines.append(line.encode('utf-8'))
214
lines.append("views:\n".encode('utf-8'))
215
for view in sorted(view_dict):
216
view_data = "%s\0%s\n" % (view, "\0".join(view_dict[view]))
217
lines.append(view_data.encode('utf-8'))
218
return b"".join(lines)
220
def _deserialize_view_content(self, view_content):
221
"""Convert a stream into view keywords and a dictionary of views."""
222
# as a special case to make initialization easy, an empty definition
223
# maps to no current view and an empty view dictionary
224
if view_content == b'':
226
lines = view_content.splitlines()
227
match = _VIEWS_FORMAT_MARKER_RE.match(lines[0])
230
"format marker missing from top of views file")
231
elif match.group(1) != b'1':
233
"cannot decode views format %s" % match.group(1))
238
for line in lines[1:]:
239
text = line.decode('utf-8')
241
parts = text.split('\0')
244
elif text == 'views:':
247
elif text.find('=') >= 0:
248
# must be a name-value pair
249
keyword, value = text.split('=', 1)
250
keywords[keyword] = value
252
raise ValueError("failed to deserialize views line %s",
254
return keywords, views
255
except ValueError as e:
256
raise ValueError("failed to deserialize views content %r: %s"
260
class DisabledViews(_Views):
261
"""View storage that refuses to store anything.
263
This is used by older formats that can't store views.
266
def __init__(self, tree):
269
def supports_views(self):
272
def _not_supported(self, *a, **k):
273
raise ViewsNotSupported(self.tree)
275
get_view_info = _not_supported
276
set_view_info = _not_supported
277
lookup_view = _not_supported
278
set_view = _not_supported
279
delete_view = _not_supported
282
def view_display_str(view_files, encoding=None):
283
"""Get the display string for a list of view files.
285
:param view_files: the list of file names
286
:param encoding: the encoding to display the files in
289
return ", ".join(view_files)
291
return ", ".join([v.encode(encoding, 'replace') for v in view_files])
294
def check_path_in_view(tree, relpath):
295
"""If a working tree has a view enabled, check the path is within it."""
296
if tree.supports_views():
297
view_files = tree.views.lookup_view()
298
if view_files and not osutils.is_inside_any(view_files, relpath):
299
raise FileOutsideView(relpath, view_files)